面试题——死锁的实现

public class DeadLock {
    public static Object Chopstick_1 = new Object();
    public static Object Chopstick_2 = new Object();

    public static void main(String[] args) {
        final DeadLock deadLock = new DeadLock();

        // 第一个线程  
        new Thread(new Runnable() {
                public void run() {
                    try {
                        synchronized (Chopstick_1) {
                            System.out.println("甲得到筷子1");
                            Thread.sleep(1000); // 当前线程睡一会,让另外一个线程保证能得到Chopstick_2的执行权  

                            synchronized (Chopstick_2) {
                                System.out.println("甲得到筷子2");
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();

        // 第二个线程  
        new Thread(new Runnable() {
                public void run() {
                    try {
                        synchronized (Chopstick_2) {
                            System.out.println("乙得到筷子2");
                            Thread.sleep(1000); // 当前线程睡一会,让另外一个线程保证能得到Chopstick_1的执行权  

                            synchronized (Chopstick_1) {
                                System.out.println("乙得到筷子1");
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
    }
}

 

你可能感兴趣的:(面试题)