多线程核心8-2:线程三大安全问题之死锁

一个必然死锁的例子

public class MultiThreadError2 implements Runnable {
    
    
    int flag = 0;
    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
    
    
        MultiThreadError2 r1 = new MultiThreadError2();
        MultiThreadError2 r2 = new MultiThreadError2();

        r1.flag = 0;
        r2.flag = 1;

        new Thread(r1).start();
        new Thread(r2).start();
    }

    @Override
    public void run() {
    
    
        System.out.println("flag : " + flag);

        if (flag == 0){
    
    
            synchronized (o1){
    
    
                try {
    
    
                    Thread.sleep(500);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                synchronized (o2){
    
    
                    System.out.println("0");
                }
            }
        }

        if (flag == 1){
    
    
            synchronized (o2){
    
    
                try {
    
    
                    Thread.sleep(500);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                synchronized (o1){
    
    
                    System.out.println("1");
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44863537/article/details/112593970