美文网首页程序员
java程序死锁的例子和排查

java程序死锁的例子和排查

作者: 月下饿狼 | 来源:发表于2020-07-10 11:35 被阅读0次
public class DeadLockDemo {
    public static void main(String[] args) {
        new Thread(new hostLockThread("lockA","lockB"),"aaaaa").start();
        new Thread(new hostLockThread("lockB","lockA"),"bbbb").start();
    }
}

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

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

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"\t 持有锁"+lockA);
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"\t 想去获取锁"+lockB);
            }
        }
    }
}

定位分析排查

E:\study>jps -l
20736
4528 DealLockDemo
13140 org.jetbrains.jps.cmdline.Launcher
19476 org.jetbrains.idea.maven.server.RemoteMavenServer36
8632 org.jetbrains.kotlin.daemon.KotlinCompileDaemon
6620 sun.tools.jps.Jps

E:\study>jstack 4528

Java stack information for the threads listed above:
===================================================
"bbbb":
        at hostLockThread.run(DealLockDemo.java:22)
        - waiting to lock <0x00000000d5ec8e68> (a java.lang.String)
        - locked <0x00000000d5ec8ea0> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"aaaaa":
        at hostLockThread.run(DealLockDemo.java:22)
        - waiting to lock <0x00000000d5ec8ea0> (a java.lang.String)
        - locked <0x00000000d5ec8e68> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.

相关文章

网友评论

    本文标题:java程序死锁的例子和排查

    本文链接:https://www.haomeiwen.com/subject/uswpcktx.html