NOTE

6.37 死锁

例子 - 查看状态

Java创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

例子

public class DeadLock
{
    private static final Object LOCK1 = new Object();
    private static final Object LOCK2 = new Object();


    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(()->{
            synchronized (LOCK1)
            {
                try
                {
                    TimeUnit.SECONDS.sleep(3);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                synchronized (LOCK2)
                {
                    System.out.println(Thread.currentThread().getName() + ":获取了两个锁");
                }
            }
        });
        Thread thread2 = new Thread(()->{
            synchronized (LOCK2)
            {
                try
                {
                    TimeUnit.SECONDS.sleep(3);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                synchronized (LOCK1)
                {
                    System.out.println(Thread.currentThread().getName() + ":获取了两个锁");
                }
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

    }
}
  • 查看状态