问题描述:一圆桌前坐着5位哲学家,两个人中间有一只筷子,桌子中央有面条。哲学家思考问题,当饿了的时候拿起左右两只筷子吃饭,必须拿到两只筷子才能吃饭。上述问题会产生死锁的情况,当5个哲学家都拿起自己右手边的筷子,准备拿左手边的筷子时产生死锁现象。
解决办法:
每个哲学家必须确定自己左右手的筷子都可用的时候,才能同时拿起两只筷子进餐,吃完之后同时放下两只筷子。
class philosopher extends Thread{
private String name;
private Fork fork;
public philosopher(String name, Fork fork) {
super(name);
this.name = name;
this.fork = fork;
}
@Override
public void run() {
while(true) {
thinking();//思考
fork.takeFork();//拿筷子
eating();//吃饭
fork.putFork();//放筷子
}
}
public void thinking() {
try {
System.out.println(name + "在思考");
sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
public void eating() {
try {
System.out.println(name + "在吃饭");
sleep(1000);
}catch (Exception e) {
System.out.println(e);
}
}
}
class Fork {
private boolean[] used = new boolean[5];//5双筷子
/*
同步执行,拿筷子操作
*/
public synchronized void takeFork() {
String name = Thread.currentThread().getName();
int x = Integer.parseInt(name);
while(used[x] || used[(x+1)%5]) {
try {
wait();//如果不能拿到两只筷子,则一直等待
}catch (Exception e) {
System.out.println(e);
}
}
used[x] = true;
used[(x+1)%5] = true;
}
/*
放筷子
*/
public synchronized void putFork() {
String name = Thread.currentThread().getName();
int x = Integer.parseInt(name);
used[x] = false;
used[(x+1)%5] = false;
notifyAll();//放下筷子后叫醒其他人
}
}
//测试一下
public class Main {
public static void main(String[] args) {
Fork fork = new Fork();
philosopher p1 = new philosopher("0", fork);
p1.start();
philosopher p2 = new philosopher("1", fork);
p2.start();
philosopher p3 = new philosopher("2", fork);
p3.start();
philosopher p4 = new philosopher("3", fork);
p4.start();
philosopher p5 = new philosopher("4", fork);
p5.start();
}
}
不会有超过两个人同时吃饭