Skip to content

Commit 8e04a57

Browse files
dead-lock
1 parent 67301dd commit 8e04a57

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

DeadLock/src/DeadLock_2.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @Author: Starry
3+
* @Date: 05-08-2022 15:16
4+
*/
5+
public class DeadLock_2 {
6+
7+
private static Object resourceA = new Object(), resourceB = new Object();
8+
9+
public static void main(String[] args) {
10+
Thread A = new Thread(() -> {
11+
synchronized (resourceA) {
12+
System.out.println(Thread.currentThread().getName() + " Get A --> ");
13+
try {
14+
Thread.sleep(1000);
15+
} catch (Exception e) {
16+
e.printStackTrace();
17+
}
18+
System.out.println(Thread.currentThread().getName() + " Waiting Get B --> ");
19+
synchronized (resourceB) {
20+
System.out.println(Thread.currentThread().getName() + " Get B --> ");
21+
}
22+
}
23+
});
24+
25+
Thread B = new Thread(() -> {
26+
// A B 顺序改变即可解除死锁
27+
synchronized (resourceB) {
28+
System.out.println(Thread.currentThread().getName() + " Get B --> ");
29+
try {
30+
Thread.sleep(1000);
31+
} catch (Exception e) {
32+
e.printStackTrace();
33+
}
34+
System.out.println(Thread.currentThread().getName() + " Waiting Get A --> ");
35+
synchronized (resourceA) {
36+
System.out.println(Thread.currentThread().getName() + " Get A --> ");
37+
}
38+
}
39+
});
40+
A.start();
41+
B.start();
42+
}
43+
44+
}

0 commit comments

Comments
 (0)