多线程死锁

public class DeadLock {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Test(true));
        Thread t2 = new Thread(new Test(false));
        t1.start();
        t2.start();

    }
}

class Test implements Runnable {
    private boolean flag;

    public Test(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        while (true) {
            if (flag) {
                synchronized (MyLock.locka) {
                    System.out.println("if" + "...." + "locka");
                    synchronized (MyLock.lockb) {
                        System.out.println("if" + "...." + "lockb");
                    }
                }
            } else {
                synchronized (MyLock.lockb) {
                    System.out.println("else" + "...." + "lockb");
                    synchronized (MyLock.locka) {
                        System.out.println("else" + "...." + "locka");
                    }
                }
            }
        }
    }
}

class MyLock {
    public static final Object locka = new Object();
    public static final Object lockb = new Object();
}

你可能感兴趣的:(Java)