线程死锁

public class DeadLockTest implements Runnable {
    public int           flag = 1;
    public static Object o1   = new Object();
    public static Object o2   = new Object();
   
    public void run() {
        System.out.println("flag 是" + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }
       
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }
   
    public static void main(String[] args) {
        DeadLockTest t1 = new DeadLockTest();
        DeadLockTest t2 = new DeadLockTest();
        t1.flag = 1;
        t2.flag = 0;
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);
        thread1.start();
        thread2.start();
    }
}
线程死锁问题代码!

你可能感兴趣的:(thread)