死锁,Java简单示例

时间:2022-02-06 17:01:54

死锁概念

多个线程互相持有对方等待的资源,导致这些线程全都阻塞。

Java简单示例

public class App {
private static final String LOCK_1 = "Lock1";
private static final String LOCK_2 = "Lock2";

public static void main(String[] args) {
new Thread1("Thread1").start();
new Thread2("Thread2").start();
}

private static class Thread1 extends Thread {
Thread1(String name) {
super(name);
}

@Override
public void run() {
synchronized (LOCK_1) {
holdingLock(LOCK_1);
sleepForSomeTime(1);
waitingLock(LOCK_2);
synchronized (LOCK_2) {
holdingLock(LOCK_2);
}
releaseLock(LOCK_2);
}
releaseLock(LOCK_1);
}
}


private static class Thread2 extends Thread {
Thread2(String name) {
super(name);
}

@Override
public void run() {
synchronized (LOCK_2) {
holdingLock(LOCK_2);
waitingLock(LOCK_1);
synchronized (LOCK_1) {
holdingLock(LOCK_1);
}
releaseLock(LOCK_1);
}
releaseLock(LOCK_2);
}
}
}

执行结果

Thread1 holding Lock1
Thread1 sleep 1s.
Thread2 holding Lock2
Thread2 waiting Lock1
Thread1 waiting Lock2

完整项目地址

https://git.coding.net/zhi-cike/dead-lock-demo.git

通过线程转存储查看是否存在死锁,当前为sun jdk使用jstack命令

利用ps查找上述代码执行线程PID,执行jstack PID,结果会直接输出到控制台
也可以输出到文件中jstack PID > dump.txt
执行结果如下
死锁,Java简单示例