Android开发手写一个简单的死锁

2021-01-30  本文已影响0人  你的益达233
public class TestDeadLock {

public static void main(String[] args) {

    Object lock1 = new Object();
    Object lock2 = new Object();

    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized(lock1) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName());
                }
            }

        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (lock2) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName());
                }
            }
        }
    }).start();

    System.out.println("主线程结束...");
}
}
上一篇下一篇

猜你喜欢

热点阅读