写一个死锁

形成死锁的原因:
1,互斥条件:线程使用的资源必须至少有一个是不能共享的;
2,请求与保持条件:至少有一个线程必须持有一个资源并且正在等待获取一个当前被其它线程持有的资源;
3,非剥夺条件:分配资源不能从相应的线程中被强制剥夺;
4,循环等待条件:第一个线程等待其它线程,后者又在等待第一个线程。
因为要产生死锁,这4个条件必须同时满足,所以要防止死锁的话,只需要破坏其中一个条件即可。

思想为:定义两个对象,将他们都加上锁a、b,线程T1、T2。T1拿住了锁a ,请求锁b;T2拿住了锁b请求锁a,在等待对方释放锁的过程中谁也不让出已获得的锁。
public class DeadLock {

    public static void main(String[] args) {

        final Object a = new Object();
        final Object b = new Object();

        new Thread() {
            @Override
            public void run() {
                synchronized (a) {
                    System.out.println("T1 got the lock of a");

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("T1 was trying to get the lock of b");

                    synchronized (b) {
                        System.out.println("T1 one win");
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                    synchronized (b) {
                        System.out.println("T2 two got the lock of b");

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        System.out.println("T2 was trying to get the lock of a");

                        synchronized (a) {
                            System.out.println("T2 win");
                        }
                    }
            }
        }.start();
    }
}
运行结果为:
T1 got the lock of a
T2 two got the lock of b
T1 was trying to get the lock of b
T2 was trying to get the lock of a

从运行的打印结果我们可以看到T1和T2各自获得了a和b锁,并且互相在尝试获取对方手里的锁,但在等待对方释放锁的过程中谁也不让出已获得的锁,谁都没有赢,则形成了死锁

原文地址:https://www.cnblogs.com/liuqing576598117/p/11205543.html