-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathThreadDeadlock.java
75 lines (68 loc) · 2.39 KB
/
ThreadDeadlock.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
71
72
73
74
75
public class ThreadDeadlock {
static boolean flag1 = false;
static boolean flag2 = false;
public static void main(String[] args) {
final String resource1 = "ratan tata";
final String resource2 = "mukesh ambani";
// t1 tries to lock resource1 then resource2
Runnable t = () -> {
synchronized (resource1) {
ThreadDeadlock.flag1 = true;
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(100);
} catch (Exception e) {
}
ThreadDeadlock.flag1 = false;
resource1.notify();
}
try {
while (ThreadDeadlock.flag2) {
resource2.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (resource2) {
ThreadDeadlock.flag2 = true;
System.out.println("Thread 1: locked resource 2");
ThreadDeadlock.flag2 = false;
resource2.notify();
}
};
Thread t1 = new Thread(t);
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
@Override
public void run() {
synchronized (resource2) {
ThreadDeadlock.flag2 = true;
System.out.println("Thread 2: locked resource 2");
try {
Thread.sleep(100);
} catch (Exception e) {
}
ThreadDeadlock.flag2 = false;
resource2.notify();
}
try {
while (ThreadDeadlock.flag1) {
resource1.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (resource1) {
ThreadDeadlock.flag1 = true;
System.out.println("Thread 2: locked resource 1");
ThreadDeadlock.flag1 = false;
resource1.notify();
}
}
};
t1.start();
t2.start();
}
}