死锁产生的条件
1. 线程A, 持有锁1,不释放,请求锁2.
2.线程B, 持有锁2, 不释放,请求锁1
Java代码模拟
public class DeadLockTest { private static Object lock1 = new Object(); private static Object lock2 = new Object(); private static int flag = 1; public static void main(String [] args) { new Thread(() -> { synchronized(lock1) { try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } synchronized(lock2) { try { sleep(200); flag = 2; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(() -> { synchronized(lock2) { try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } synchronized(lock1) { try { sleep(200); flag = 3; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(() -> { while(flag == 1) { try { sleep(200); System.out.println("死锁"); } catch (InterruptedException e) { e.printStackTrace(); } } if (flag == 2) { System.out.println("未死锁2"); } if (flag == 3) { System.out.println("未死锁3"); } }).start(); }
运行输出
使用jstack输出thead dump文件
jstack ****(pid) > output.txt
打开output.txt文件