手写Java线程死锁

April 14, 2019

如果运行结果没有同时出现 o1没出现死锁o2没出现死锁,表示两个线程已死锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class DeadLockClass {
    public static void main(String[] args) {
        new Thread(new DeadLock(true)).start();
        new Thread(new DeadLock(false)).start();
    }

    private static class DeadLock implements Runnable {
        private boolean mFlag;
        private static final Object LOCK_0 = new Object();
        private static final Object LOCK_1 = new Object();

        public DeadLock(boolean flag) { mFlag = flag; }

        public void run() {
            synchronized (mFlag ? LOCK_0 : LOCK_1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignore) {
                }

                synchronized (mFlag ? LOCK_1 : LOCK_0) {
                    System.out.println("o1没出现死锁");
                }
            }
        }
    }
}