使用synchronized模拟线程死锁,sleep不会自动释放锁,wait会释放锁
package com.mythread;/*** @author TANGSHUAI* @date 2021年4月1日 上午10:39:03* 模拟synchronized死锁*/public class Test {public static void main(String[] args) {Eat m=new Eat(0,"张三");Eat m2=new Eat(1,"李四");m.sta
·
package com.mythread;
/**
* @author TANGSHUAI
* @date 2021年4月1日 上午10:39:03
* 模拟synchronized死锁
*/
public class Test {
public static void main(String[] args) {
Eat m=new Eat(0,"张三");
Eat m2=new Eat(1,"李四");
m.start();
m2.start();
}
}
//碗
class Bowl {
}
//筷子
class Chopsticks {
}
//吃饭
class Eat extends Thread {
// 需要在资源只有一份
static Chopsticks chopsticks = new Chopsticks();
static Bowl bowl = new Bowl();
int choice;// 选择吃饭工具
String name;// 吃饭的人
Eat(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
//吃饭
try {
eat();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void eat() throws InterruptedException {
if(choice==0) {
synchronized (bowl) {
System.out.println(this.name+"吃饭拿碗");
Thread.sleep(1000);
//bowl.wait(1000);
//
synchronized (chopsticks) {
System.out.println(this.name+"吃饭拿筷子");
}
}
}else {
synchronized (chopsticks) {
System.out.println(this.name+"吃饭拿筷子");
Thread.sleep(2000);
//chopsticks.wait(2000);
//
synchronized (bowl) {
System.out.println(this.name+"吃饭拿碗");
}
}
}
}
}
更多推荐



所有评论(0)