第十章-死锁编码及定位分析

是什么

image-20191107112214586

案例

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
/**
* @desc 死锁
* @Author xw
* @Date 2019/8/23
*/
public class DeadLockDemo {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new HoldLockThread(lockA, lockB), "AAA").start();
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
new Thread(new HoldLockThread(lockB, lockA), "BBB").start();
}
}

class HoldLockThread implements Runnable {
private String lockA;
private String lockB;

public HoldLockThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}

@Override
public void run() {
synchronized (lockA) { // 锁A执有锁B
System.out.println(Thread.currentThread().getName() + "\t 自己执有:" + lockA + "\t 尝试获取:" + lockB);
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
synchronized (lockB) {
System.out.println(Thread.currentThread().getName() + "\t 自己执有:" + lockB + "\t 尝试获取:" + lockA);
}
}
}
}

如何解决

  1. jps命令定位进程号

    $ jsp -l

  2. jstack死锁查看

    $ jstack 进程号