-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeadLock.java
49 lines (43 loc) · 1.26 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
package com.zzhow.synchronized_;
/**
* 2024年5月2日
*
* @author ZZHow
* 模拟线程死锁
*/
public class DeadLock {
public static void main(String[] args) {
DeadLockThread threadA = new DeadLockThread(true);
DeadLockThread threadB = new DeadLockThread(false);
threadA.setName("threadA");
threadB.setName("threadB");
threadA.start();
threadB.start();
}
}
class DeadLockThread extends Thread {
private static Object o1 = new Object();
private static Object o2 = new Object();
private boolean flag;
public DeadLockThread(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + " 进入 1");
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "进入 2");
}
}
} else {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " 进入 3");
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "进入 4");
}
}
}
}
}