1. 问题描述
一桌5个人,拥有5根筷子,每隔人必须拿到两个筷子才能吃饭,吃完就会放下筷子。
若每个人同事去抢自己右手边的筷子,那么大家都可以获取一根筷子,但大家都在等待另一只筷子,形成了死锁。
2.解决方法
设置某个人是先获取左手边的筷子,即可解决问提。但若是设置特定某个人就是使得整体顺序一直保持一样,所以考虑奇数编号拿左边筷子,偶数编码拿右手筷子。
3.代码解决实现方式如下:
package com.current.demo01.eat;
// 筷子类
public class ChapStick {
}
package com.current.demo01.eat;
import lombok.SneakyThrows;
// 人物类,抢筷子方法
public class Persion extends Thread{
private ChapStick left;
private ChapStick right;
private int index;
public Persion(String name,int index,ChapStick left,ChapStick right){
this.setName(name);
this.index = index;
this.left = left;
this.right = right;
}
@SneakyThrows
@Override
public void run() {
if(index%2==0){
synchronized (left){
Thread.sleep(index+1);
synchronized (right){
Thread.sleep(index+1);
System.out.println(index+"号人员已就餐完毕");
}
}
}else {
synchronized (right){
Thread.sleep(index+1);
synchronized (left){
Thread.sleep(index+1);
System.out.println(index+"号人员已就餐完毕");
}
}
}
}
}
package com.current.demo01.eat;
// 启动5个人开始抢筷子
public class EatTest {
public static void main(String[] args){
// 创建5个筷子对象
ChapStick chapStick1 = new ChapStick();
ChapStick chapStick2 = new ChapStick();
ChapStick chapStick3 = new ChapStick();
ChapStick chapStick4 = new ChapStick();
ChapStick chapStick5 = new ChapStick();
// 创建5个人抓筷子
Persion persion1 = new Persion("no1",1,chapStick1,chapStick2);
Persion persion2 = new Persion("no2",2,chapStick2,chapStick3);
Persion persion3 = new Persion("no3",3,chapStick3,chapStick4);
Persion persion4 = new Persion("no4",4,chapStick4,chapStick5);
Persion persion5 = new Persion("no5",5,chapStick5,chapStick1);
persion1.start();
persion2.start();
persion3.start();
persion4.start();
persion5.start();
}
}