----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
哲学家就餐:有五个哲学家绕着圆桌坐,每个哲学家面前有一碗面,两人之间有一支筷子,这样每个哲学家左右各有一支筷子。哲学家有2个状态,思考或者拿起筷子吃饭。如果哲学家拿到一只筷子,不能吃饭,直到拿到2只才能吃饭,并且一次只能拿起身边的一支筷子。一旦拿起便不能放下直到把饭吃完,此时才把这双筷子放回原处。如果,很不幸地,每个哲学家拿起他或她左边的筷子,那么就没有人可以吃到饭了。这就会造成了死锁……
我试着编了代码,但只能一个人吃,不知道在保证不死锁的情况下怎样才能让两个人同时吃。
import java.util.concurrent.locks.*;
public class PhilosopherProblem {
public static void main(String[] args){
Fork f1=new Fork("叉子一号");
Fork f2=new Fork("叉子二号");
Fork f3=new Fork("叉子三号");
Fork f4=new Fork("叉子四号");
Fork f5=new Fork("叉子五号");
Lock lock = new ReentrantLock();
Food food = new Food(100);
new Thread(new Philosopher("哲学家A",f1,f2,lock,food)).start();
new Thread(new Philosopher("哲学家B",f2,f3,lock,food)).start();
new Thread(new Philosopher("哲学家C",f3,f4,lock,food)).start();
new Thread(new Philosopher("哲学家D",f4,f5,lock,food)).start();
new Thread(new Philosopher("哲学家E",f5,f1,lock,food)).start();
}
}
//Food类
class Food{
int food;
public Food(int food){
this.food = food;
}
public int eat(){
return food--;
}
public int has(){
return food;
}
}
//叉子类
class Fork{
String name;
boolean flag=true;//构造方法
public Fork(String name){
this.name=name;
}
//放下叉子
public synchronized void putdown(){
this.flag=true;
this.notifyAll();
}
//去取叉子
public synchronized void pickup(){
try{
while(flag==false){
this.wait();
}
this.flag=false;
}
catch(Exception e){}
}
}
//哲学家类:
class Philosopher implements Runnable{
String name;
Fork left;
Fork right;
Lock lock;
Food food;
public Philosopher(String name,Fork left,Fork right,Lock lock,Food food){
this.name = name;
this.left = left;
this.right = right;
this.lock = lock;
this.food = food;
}
public void run(){
//吃饭前的思考,时间是随机的
while(true){
try{
System.out.println(name+"在思考中。。。");
Thread.sleep((long)(Math.random()*10));//思考时间
System.out.println(name+"思考结束!");
}
catch(InterruptedException e){
e.printStackTrace();
}
lock.lock();
left.pickup();
System.out.println(name+"抓起"+left.name);
right.pickup();
System.out.println(name+"抓起"+right.name);
if(food.has()>0){
System.out.println(name+"拿到两支叉子开吃:"+food.eat());
lock.unlock();
}
else{
lock.unlock();
System.out.println(name+"……food已经被吃完了");
left.putdown();
right.putdown();
break;
}
try{
Thread.sleep(20);//吃饭时间
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name+"吃饱之后放下了"+left.name+"和"+right.name+"!");
left.putdown();
right.putdown();
}
System.out.println(name+"……gameover");
}
}
这个问题,看了网上也有一些解决方案,但是感觉都挺繁琐的。