死锁(实现)

public class DeadLock {

    static StringBuffer sb1 = new StringBuffer();
    static StringBuffer sb2 = new StringBuffer();


    public static void main(String[] args) {
        new Thread(()->{
            synchronized(sb1){
                sb1.append("A");
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(sb2){
                    sb2.append("B");
                    System.out.println(sb1.toString());
                    System.out.println(sb2.toString());
                }
            }
        }).start();

        new Thread(()->{
            synchronized(sb2){
                sb1.append("C");
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(sb1){
                    sb2.append("D");
                    System.out.println(sb1.toString());
                    System.out.println(sb2.toString());
                }
            }
        }).start();
    }
}
原文地址:https://www.cnblogs.com/kaibing/p/9233382.html