鱼与熊掌不能兼得
public class Demo04 {
public static void main(String[] args) {
Eat person1 = new Eat(0,"小王");
Eat person2 = new Eat(1,"小李");
person1.start();
person2.start();
}
}
class Fish{
String mc = "吃鱼!";
}
class Bear{
String mc = "吃熊掌!";
}
class Eat extends Thread{
//需要的资源只有一份,用static来表示
static Fish fish = new Fish();
static Bear bear = new Bear();
int choice;
String name;
public Eat(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
eat();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//吃饭,互相持有对方的锁,需要拿到对方的资源
private void eat() throws InterruptedException {
if (choice == 0){
synchronized (fish){
System.out.println(this.name+fish.mc);
Thread.sleep(1000);
synchronized (bear){ //一秒钟后吃熊掌
System.out.println(this.name+bear.mc);
}
}
}else {
synchronized (bear){
System.out.println(this.name+bear.mc);
Thread.sleep(1000);
synchronized (fish){ //一秒钟后吃鱼
System.out.println(this.name+fish.mc);
}
}
}
}
}
-
解决死锁:当小王想要抢小明手中熊掌的时候,必须等待对方释放锁后,才能拿得到,不在产生死锁
public class Demo04 {
public static void main(String[] args) {
Eat person1 = new Eat(0,"小王");
Eat person2 = new Eat(1,"小李");
person1.start();
person2.start();
}
}
class Fish{
String mc = "吃鱼!";
}
class Bear{
String mc = "吃熊掌!";
}
class Eat extends Thread{
//需要的资源只有一份,用static来表示
static Fish fish = new Fish();
static Bear bear = new Bear();
int choice;
String name;
public Eat(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
eat();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//吃饭,互相持有对方的锁,需要拿到对方的资源
private void eat() throws InterruptedException {
if (choice == 0){
synchronized (fish){
System.out.println(this.name+fish.mc);
Thread.sleep(1000);
}
synchronized (bear){ //一秒钟后吃熊掌
System.out.println(this.name+bear.mc);
}
}else {
synchronized (bear){
System.out.println(this.name+bear.mc);
Thread.sleep(1000);
}
synchronized (fish){ //一秒钟后吃鱼
System.out.println(this.name+fish.mc);
}
}
}
}