死锁是指两个或者两个以上的线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉那么它们都将无法推进下去
模拟死锁
class HoldLockThread extends Thread { private String lockA; private String lockB; public HoldLockThread(String lockA, String lockB) { this.lockA = lockA; this.lockB = lockB; } @Override public void run() { synchronized (lockA) { System.out.println("线程" + Thread.currentThread().getName() + "持有锁" + lockA + ",尝试获取锁" + lockB); try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) { e.printStackTrace(); } synchronized (lockB) { System.out.println("线程" + Thread.currentThread().getName() + "持有锁" + lockB); } } } } public class DeadLockDemo { public static void main(String[] args) { String lockA = "lockA"; String lockB = "lockB"; new Thread(new HoldLockThread(lockA, lockB), "A").start(); new Thread(new HoldLockThread(lockB, lockA), "B").start(); } }
如何定位死锁问题?
1、先通过jps命令找到java进程pid
22208 Launcher 22209 DeadLockDemo 75993 22570 Jps
2、运行jstack pid,会自动识别可能的死锁
Found one Java-level deadlock: ============================= "B": waiting to lock monitor 0x00007fca8f813f68 (object 0x000000076accf6b0, a java.lang.String), which is held by "A" "A": waiting to lock monitor 0x00007fca8f816958 (object 0x000000076accf6e8, a java.lang.String), which is held by "B" Java stack information for the threads listed above: =================================================== "B": at com.study.demo.HoldLockThread.run(DeadLockDemo.java:25) - waiting to lock <0x000000076accf6b0> (a java.lang.String) - locked <0x000000076accf6e8> (a java.lang.String) at java.lang.Thread.run(Thread.java:748) "A": at com.study.demo.HoldLockThread.run(DeadLockDemo.java:25) - waiting to lock <0x000000076accf6e8> (a java.lang.String) - locked <0x000000076accf6b0> (a java.lang.String) at java.lang.Thread.run(Thread.java:748) Found 1 deadlock.标签:lockB,lang,lockA,java,String,Thread,死锁 From: https://www.cnblogs.com/damour-damocles/p/18608278