-
Notifications
You must be signed in to change notification settings - Fork 7
/
Deadlock.java
70 lines (56 loc) · 1.58 KB
/
Deadlock.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package chapter11;
//An example of Deadlock
class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("A Interrupted");
}
System.out.println("Trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("Inside A.last()");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " Entered B.bar()");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("B Interrupted");
}
System.out.println("Trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("Inside B.last()");
}
}
public class Deadlock implements Runnable {
A a = new A();
B b = new B();
Thread t;
Deadlock() {
Thread.currentThread().setName("Main Thread");
t = new Thread(this, "Racing Thread");
}
void deadlockStart() {
t.start();
a.foo(b); //get lock on a in this thread;
System.out.println("Back in the main thread");
}
public void run() {
b.bar(a); //get lock on b in other thread
System.out.println("Back in other thread");
}
public static void main(String[] args) {
Deadlock d1 = new Deadlock();
d1.deadlockStart();
}
}