【Java】【死锁】多线程死锁问题

1、多个线程死锁实例

(1)两个线程发生死锁

两个线程,两把锁产生死锁的代码实例

public class demo {
    public static void main(String[] args) {
        Object locker1 = new Object();
        Object locker2 = new Object();

        Thread thread1 = new Thread(()->{
            synchronized (locker1){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (locker2){
                    System.out.println("线程1进行了加锁");
                }
            }
        });

        Thread thread2 = new Thread(()->{
            synchronized (locker2){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (locker1){
                    System.out.println("线程2进行了加锁");
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}

运行上述代码,由于发生死锁,运行不出结果

产生死锁的原因是:

一开始,线程1拿到了locker1的琐,线程2拿到了locker2的琐

接着,线程1想拿到locker2,此时线程2还没有释放locker1;与此同时,线程2想拿locker1,而线程1还没有释放locker1

两个线程在这里发生僵持,便产生了死锁

(2)多个线程发生死锁

对于N个线程,M把锁发生死锁,可见哲学家进餐问题

2、嵌套与并行

上述多线程发生死锁一定是建立在加锁时是嵌套关系下

如果是并行关系,则不会发生死锁。如

public class demo {
    public static void main(String[] args) {
        Object locker1 = new Object();
        Object locker2 = new Object();

        Thread thread1 = new Thread(()->{
            synchronized (locker1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            
            synchronized (locker2){
                System.out.println("线程1进行了加锁");
            }

        });

        Thread thread2 = new Thread(()->{
            synchronized (locker2) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            synchronized (locker1){
                System.out.println("线程2进行了加锁");
            }
        });

        thread1.start();
        thread2.start();
    }
}

上述代码则不会发生死锁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沙河板混

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值