欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

死锁编码及定位分析

程序员文章站 2022-04-17 22:39:05
...

死锁 是两个或两个以上的线程在执行过程中,因争夺资源而造成的一种互相等待现象,若无外力干涉那他们都将无法推进下去。

产生原因:
系统资源不足
资源分配不当

解决:

jps命令定位进程号
jstack找到死锁查看

C:\Program Files\Java\jdk1.8.0_181\bin\jps.exe
C:\Program Files\Java\jdk1.8.0_181\bin\jstack.exe





死锁代码演示:
互相持有对方的锁

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

    public HoldLock(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.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + " 持有 " + lockB + ",想要获得 " + lockA);
            }
        }
    }
}

public class DeadLockDemo {

    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        
        new Thread(new HoldLock(lockA, lockB), "ThreadA").start();
        new Thread(new HoldLock(lockB, lockA), "ThreadB").start();
    }

}

ThreadA 持有 lockA,想要获得 lockB
ThreadB 持有 lockB,想要获得 lockA
E:\ideaProjects\suanfa>jps -l
12804 com.suanfa.booking.DeadLockDemo
12564
12484 org.jetbrains.idea.maven.server.RemoteMavenServer
10436 sun.tools.jps.Jps
12032 org.jetbrains.jps.cmdline.Launcher

E:\ideaProjects\suanfa>jstack 12804
...
...
Java stack information for the threads listed above:
===================================================
"ThreadB":
        at com.suanfa.booking.HoldLock.run(DeadLockDemo.java:28)
        - waiting to lock <0x00000000d6095058> (a java.lang.String)
        - locked <0x00000000d6095090> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"ThreadA":
        at com.suanfa.booking.HoldLock.run(DeadLockDemo.java:28)
        - waiting to lock <0x00000000d6095090> (a java.lang.String)
        - locked <0x00000000d6095058> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.