死锁

  • Post author:
  • Post category:其他


package com.atguigu.thread.deadlock;

public class DeadLockDemo
{
    public static void main(String[] args)
    {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThread(lockA, lockB), "AAA").start();
        new Thread(new HoldLockThread(lockB, lockA), "BBB").start();

    }
}


class HoldLockThread implements Runnable
{
    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() + "\t自己持有:" + lockA + "\t尝试获取" + lockB);
            try
            {
                Thread.sleep(2000L);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            synchronized (lockB)
            {
                System.out.println(
                    Thread.currentThread().getName() + "\t自己持有:" + lockB + "\t尝试获取" + lockA);
            }
        }
    }

}

运行之后:

死锁的排查:

在对应文件的目录下打开cmd窗口,输入jps -l 查看进程号

再执行jstack 进程号:来分析原因



版权声明:本文为weixin_40264444原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。