写一个死锁

死锁

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
public class Test03 {

Object lock1 = new Object();
Object lock2 = new Object();

public void method1() {
synchronized (lock1) {
synchronized (lock2) {
System.out.println("method 1 .... ");
}
}
}

public void method2() {
synchronized (lock2) {
synchronized (lock1) {
System.out.println("method 2 .... ");
}
}
}

public static void main(String[] args) {
Test03 test03 = new Test03();
new Thread(() -> {
while (true) {
test03.method1();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();

new Thread(() -> {
while (true) {
test03.method2();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}

执行结果:

1
2
3
> Task :Test03.main()
method 1 ....
method 2 ....

发生死锁,打印也被阻塞

检测死锁:

  1. jvisualvm 工具 ,
  2. 命令行工具
    jps 找到我们运行的程序 pid
    jstck pid