gzc911

线程死锁的原因:

同步中嵌套同步,但是锁却不同

死锁演示(DeadLockDemo):

class Test implements Runnable
{
    private boolean flag;
    //构造函数中传入标记的值,用来操作run方法中的if else循环
    Test(boolean flag)
    {
        this.flag = flag;
    }

    public void run()
    {
        if(flag)
        {
            while(true)
            {
                synchronized(MyLock.lockA)
                {
                    System.out.println(Thread.currentThread().getName()+"...if lockA ");
                    synchronized(MyLock.lockB)
                    {
                        System.out.println(Thread.currentThread().getName()+"..if lockB");                    
                    }
                }
            }
        }
        else
        {
            while(true)
            {
                synchronized(MyLock.lockB)
                {
                    System.out.println(Thread.currentThread().getName()+"..else lockB");
                    synchronized(MyLock.lockA)
                    {
                        System.out.println(Thread.currentThread().getName()+".....else lockA");
                    }
                }
            }
        }
    }
}

//放置了两个锁
class MyLock
{
    static Object lockA = new Object();
    static Object lockB = new Object();
}

class  DeadLockTest
{
    public static void main(String[] args) 
    {
        //传入true使其在if循环中
        Thread t1 = new Thread(new Test(true));
        //传入false使其在if循环中
        Thread t2 = new Thread(new Test(false));
        t1.start();
        t2.start();
    }
}
DeadLockDemo

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-09-28
  • 2021-11-23
  • 2018-07-29
  • 2022-01-03
  • 2022-02-27
  • 2021-11-21
猜你喜欢
  • 2022-12-23
  • 2022-02-26
  • 2021-11-04
  • 2021-12-03
相关资源
相似解决方案