-
Notifications
You must be signed in to change notification settings - Fork 1
/
DeadlockExample.java
49 lines (37 loc) · 1.39 KB
/
DeadlockExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class DeadlockExample {
public static void main(String[] args) {
Runnable r1 = () -> {
System.out.println(Thread.currentThread().getName() + " I will attempt to take String lock");
synchronized (String.class) {
System.out.println(Thread.currentThread().getName() + " Hello I have taken lock on String");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " I will attempt to take Integer lock");
synchronized (Integer.class) {
System.out
.println(Thread.currentThread().getName() + " Now I have taken a lock on Integer as well");
}
}
};
new Thread(r1).start();
Runnable r2 = () -> {
System.out.println(Thread.currentThread().getName() + " I will attempt to take Integer lock");
synchronized (Integer.class) {
System.out.println(Thread.currentThread().getName() + " Hello I have taken lock on Integer");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " I will attempt to take String lock");
synchronized (String.class) {
System.out.println(Thread.currentThread().getName() + " Now I have taken a lock on String as well");
}
}
};
new Thread(r2).start();
}
}