面试题:使用java多线程来模拟死锁

方式一

package com.coderman.juc.synchronizedtest;

/**
 * @Author zhangyukang
 * @Date 2020/6/19 16:11
 * @Version 1.0
 **/
public class DeathLockTest implements Runnable {
    private static Object lock1 = new Object();
    private static Object lock2 = new Object();

    private int flag ;

    public static void main(String[] args) {
        DeathLockTest deathLockTest1 = new DeathLockTest();
        DeathLockTest deathLockTest2= new DeathLockTest();
        deathLockTest1.flag=1;
        Thread t1 = new Thread(deathLockTest1);
        t1.start();

        deathLockTest2.flag=2;
        Thread t2 = new Thread(deathLockTest2);
        t2.start();
    }

    @Override
    public void run() {
        if (flag == 1) {
            synchronized (lock1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                }
                System.out.println(Thread.currentThread().getName() + "do something");
            }
        }

        if (flag == 2) {
            synchronized (lock2) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                }
                System.out.println(Thread.currentThread().getName() + "do something");
            }
        }

    }


}

方式二

package com.coderman.juc.synchronizedtest;

/**
 * @Author zhangyukang
 * @Date 2020/6/19 16:11
 * @Version 1.0
 **/
public class DeathLockTest2 {
    public static void main(String[] args) {
        Object lock1 = new Object();
        Object lock2 = new Object();

        new Thread(() -> {
            synchronized (lock1) {
                System.out.println("method1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {

                }
                System.out.println("do something");
            }
        }).start();

        new Thread(() -> {
            synchronized (lock2) {
                System.out.println("method2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {

                }
                System.out.println("do something");
            }
        }).start();

    }
}

# Java   多线程  

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×