死锁(实现)

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();
    }
}

 

posted @ 2018-06-27 12:48  楷兵  阅读(117)  评论(0编辑  收藏  举报