死锁

死锁是指:两个或两个以上的进程在执行过程中,由于竞争资源,或者由于彼此通信而造成的一种阻塞的现象。若无外力作用。他们都无法运行下去

小孩抢玩具(死锁)

package com.Luoking.Thread;
public class Deadlock {
public static void main(String[] args) {
playTools boy1 = new playTools("boy1","excavator");
playTools boy2 = new playTools("boy2","gun");
new Thread(boy1).start();
new Thread(boy2).start();
}
}
//枪
class gun {
}
//挖掘机
class excavator {
}
//两个小孩玩玩具
class playTools implements Runnable {
//保证玩具都只有一个 static
private static gun gun = new gun();
private static excavator excavator = new excavator();
//小孩名字
String name;
//小孩手上原先的玩具;
String tool;
//构造有参函数
public playTools(String name, String tool) {
this.name = name;
this.tool = tool;
}
@Override
public void run() {
try {
play();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void play() throws InterruptedException {
if (tool.equals("excavator")) {
synchronized (excavator) {
System.out.println(name + " get " + "excavator" + " play 2 S");
Thread.sleep(2000);
synchronized (gun) {
System.out.println(name + " get " + "gun");
}
}
} else {
synchronized (gun) {
System.out.println(name + " get " + "gun" + " play 2 S");
Thread.sleep(2000);
synchronized (excavator) {
System.out.println(name + " get " + "excavator");
}
}
}
}
}

解决死锁问题
当需要另一个对象时,需要释放已有对象的锁

package com.Luoking.Thread;
public class Deadlock {
public static void main(String[] args) {
playTools boy1 = new playTools("boy1", "excavator");
playTools boy2 = new playTools("boy2", "gun");
new Thread(boy1).start();
new Thread(boy2).start();
}
}
//枪
class gun {
}
//挖掘机
class excavator {
}
//两个小孩玩玩具
class playTools implements Runnable {
//保证玩具都只有一个 static
private static gun gun = new gun();
private static excavator excavator = new excavator();
//小孩名字
String name;
//小孩手上原先的玩具;
String tool;
//构造有参函数
public playTools(String name, String tool) {
this.name = name;
this.tool = tool;
}
@Override
public void run() {
try {
play();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void play() throws InterruptedException {
if (tool.equals("excavator")) {
synchronized (excavator) {
System.out.println(name + " get " + "excavator" + " play 2 S");
Thread.sleep(2000);
}
synchronized (gun) {
System.out.println(name + " get " + "gun");
}
} else {
synchronized (gun) {
System.out.println(name + " get " + "gun" + " play 2 S");
Thread.sleep(2000);
}
synchronized (excavator) {
System.out.println(name + " get " + "excavator");
}
}
}
}
posted @   小罗要有出息  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示