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资源");
}
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?