21 死锁


死锁,前提是资源唯一且被锁住 synchronized

package ThreadDemo;

// 死锁问题
public class Test21_DeadLock {
    public static void main(String[] args) {
        new Thread(new DeadLock(0),"a线程").start();
        new Thread(new DeadLock(1),"b线程").start();
    }
}

// A资源
class A{ }

// B 资源
class B{ }

// 死锁
class DeadLock implements Runnable{
    // 资源唯一才会引发死锁
    static A a=new A();
    static B b=new B();
    int choice;
    public DeadLock(int choice){
        this.choice=choice;
    }
    @Override
    public void run() {
        try {
            choice();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public void choice() throws InterruptedException {
        if (choice==0){
            synchronized (a){  // 先获得a,再获得b;等两个资源都拿到之后才释放
                System.out.println(Thread.currentThread().getName()+"获得了a资源");
                Thread.sleep(1000);  // 等待其他线程获得b,形成死锁
                synchronized (b){
                    System.out.println(Thread.currentThread().getName()+"获得了b资源");
                }
            }
        }else {
            synchronized (b){  // 先获得b,再获得a;等两个资源都拿到之后才释放
                System.out.println(Thread.currentThread().getName()+"获得了b资源");
                Thread.sleep(1000);  // 等待其他线程获得b,形成死锁
                synchronized (a){
                    System.out.println(Thread.currentThread().getName()+"获得了a资源");
                }
            }
        }
    }
}
posted @   被占用的小海海  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示