java的死锁问题

/**
 * 用sleep仅仅是增加的死锁的概率,不用sleep线程照样会有死锁
 * 出现了死锁问题,当第一个线程锁住了sb1并且sleep时,
 * 第二个线程锁住了sb2,
 * 然后sb1一直在等线程2释放sb2锁,
 * 同样sb2一直在等线程1释放sb1锁,
 * 这就产生了死锁情况
 */

public class TestDeadLock {
    public static void main(String[] args) {
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        new Thread(){
            @Override
            public void run() {
                synchronized (sb1){

                    sb1.append("a");
                    sb2.append("1");

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

                    synchronized (sb2){
                        sb1.append("b");
                        sb2.append("2");
                        System.out.println(sb1);
                        System.out.println(sb2);
                    }

                }
            }
        }.start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (sb2){

                    sb1.append("c");
                    sb2.append("3");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                    synchronized (sb1){
                        sb1.append("d");
                        sb2.append("4");
                        System.out.println(sb1);
                        System.out.println(sb2);
                    }
                }
            }
        }).start();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44833767/article/details/105449128