写一个必然死锁的例子

示例代码

public class TestMain implements Runnable {

    //定义两把锁
    static Object lock1 = new Object();
    static Object lock2 = new Object();
    //定义一个标志位,方便执行不同逻辑
    int flag;

    @Override
    public void run() {
        if (flag == 1) {
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + "获取到了lock1");
                System.out.println(Thread.currentThread().getName() + "等待获取lock2");
                try {
                    //睡眠500毫秒,确保线程二已经拿到了lock2
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "获取到了lock2");
                }
            }
            System.out.println(Thread.currentThread().getName() + "运行结束");
        }
        if (flag == 2) {
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "获取到了lock2");
                System.out.println(Thread.currentThread().getName() + "等待获取lock1");
                try {
                    //睡眠500毫秒,确保线程一已经拿到了lock1
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "获取到了lock1");
                }
            }
            System.out.println(Thread.currentThread().getName() + "运行结束");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestMain testMain1 = new TestMain();
        testMain1.flag = 1;
        Thread thread = new Thread(testMain1, "线程一");
        TestMain testMain2 = new TestMain();
        testMain2.flag = 2;
        Thread thread1 = new Thread(testMain2, "线程二");
        thread.start();
        thread1.start();
    }
}

运行结果如下:
在这里插入图片描述
可以发现线程一在等lock2锁,而线程二在等lock1锁,但是两者只有先得到对方的锁才能够释放出对方所需要的锁,这样就进入了无限等待的情况,发生了死锁。可以发现这时程序其实还是在运行的。

如果我们强行停止程序,会出现如下情况:
在这里插入图片描述
可以发现code不再是正常的0,而是130了。

总结

面试有时候会让手写一个死锁的例子,最简单的死锁例子就是这个了。

发布了242 篇原创文章 · 获赞 250 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/104647117