哲学家进餐问题描述有五个哲学家,他们的生活方式是交替地进行思考和进餐,哲学家们共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上有五个碗和五支筷子,平时哲学家进行思考,饥饿时便试图取其左、右最靠近他的筷子,只有在他拿到两支筷子时才能进餐,该哲学家进餐完毕后,放下左右两只筷子又继续思考。
约束条件
(1)只有拿到两只筷子时,哲学家才能吃饭。
(2)如果筷子已被别人拿走,则必须等别人吃完之后才能拿到筷子。
代码实现:这个版本的代码直接进行判断2 个筷子的状态
代码如下:
class Taskdemo implements Runnable{
//初始化筷子的使用状态为false
private boolean[] chopstick = {false,false,false,false,false};
@Override
public void run() {
//模拟哲学家的活动
while(true) {
//思考
System.out.println("哲学家"+Thread.currentThread().getName()+"思考");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//吃饭
synchronized (this) {
//获取两只筷子的状态,
int num = Integer.parseInt(Thread.currentThread().getName());
//取余将4号哲学家应该取的是0号的筷子
if(chopstick[num]||chopstick[(num+1)%5]) {
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//当筷子的使用状态为false,使用筷子吃饭
chopstick[num] = true;
chopstick[(num+1)%5] = true;
System.out.println(Thread.currentThread().getName()+"吃饭");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//重置筷子的状态属性
int num1 = Integer.parseInt(Thread.currentThread().getName());
synchronized (this) {
chopstick[num1] = false;
chopstick[(num1+1)%5] = false;
}
}
}
}
public class PhilosopherEating {
public static void main(String[] args) {
Taskdemo taskdemo = new Taskdemo();
Thread thread1 = new Thread(taskdemo, "0");
Thread thread2 = new Thread(taskdemo, "1");
Thread thread3 = new Thread(taskdemo, "2");
Thread thread4 = new Thread(taskdemo, "3");
Thread thread5 = new Thread(taskdemo, "4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}