Java多线程的一个死锁程序

锁类

public class MyLock 
{
    public static Object lock_a = new Object();
    public static Object lock_b = new Object();
}

线程类

public class DeadLockTest implements Runnable
{
    private boolean flag ;
    
    public DeadLockTest(boolean flag)
    {
        this.flag = flag;
    }
    
    @Override
    public void run() 
    {
        if(flag)
        {
            while(true)
            synchronized(MyLock.lock_a)
            {
                System.out.println(Thread.currentThread().getName()+"...lock_a...");
                synchronized(MyLock.lock_b)
                {
                    System.out.println(Thread.currentThread().getName()+"...lock_b...");
                }
            }
        }
        else
        {
            while(true)
            synchronized(MyLock.lock_b)
            {
                System.out.println(Thread.currentThread().getName()+"...lock_b...");
                synchronized(MyLock.lock_a)
                {
                    System.out.println(Thread.currentThread().getName()+"...lock_a...");
                }
            }
        }
    }

}

测试代码

import org.junit.Test;

public class DeadLock 
{
    DeadLockTest a = new DeadLockTest(true);
    DeadLockTest b = new DeadLockTest(false);
    
    Thread t1 = new Thread(a);
    Thread t2 = new Thread(b);
    
    @Test
    public void TestDeadLock()
    {
        t1.start();
        t2.start();
    }
    
}
原文地址:https://www.cnblogs.com/xiayangqiushi/p/3363037.html