Java:创造一个简单的死锁环境

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/new_Aiden/article/details/72457668

只作为记录

public class Main {

    private static final Object oneLock = new Object();
    private static final Object twoLock = new Object();

    public static void main(String[] args) {
        new OneThread().start();
        new TwoThread().start();
    }

    private static class OneThread extends Thread {
        @Override
        public void run() {
            synchronized (oneLock) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (twoLock) {
                    System.out.println("one");
                }
            }
        }
    }

    private static class TwoThread extends Thread {
        @Override
        public void run() {
            synchronized (twoLock) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (oneLock) {
                    System.out.println("two");
                }
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/new_Aiden/article/details/72457668