本文对多线程中经典问题-哲学家就餐问题用Java语言描述,给出了三种常见的解决方法,实现了其中的两种。
一、问题描述:
在一个圆桌上,有n个哲学家,n只筷子,每个哲学家左右两边各返一只筷子。哲学家可以进行思考和吃饭,思考时,不获取筷子。吃饭时,必须同时获得左右两只筷子才能吃饭(先获取左边的再获取右边的)。
二、Java实现哲学家就餐问题
实现Chopstick类,每个筷子有个编号index,还有个属性isUsing表示是否正在使用,如果isUsing为true,后访问的哲学家对象就必须等待直到isUsing为false才能访问
package Blog.philosopher;
public class Chopstick {
private int index;
private boolean isUsing = false;
public Chopstick(int index){
this.index = index;
}
//修改toString方法,因为System.out.println()输出对象都是调用toString方法
@Override
public String toString() {
return "Chopstick [index = " + index + "]";
}
//对于一个成员方法加synchronized关键字,作用范围是从调用该方法开始,作用对象是该方法所在的对象
public synchronized void take() throws InterruptedException{
while(isUsing){
wait();
}
isUsing = true;
}
//使用结束,通知所有其他线程
public synchronized void drop(){
isUsing = false;
notifyAll();
}
public int getIndex() {
return index;
}
public boolean getIsUsing(){
return isUsing;
}
}
实现Philosopher类
package Blog.philosopher;
public class Philosopher implements Runnable{
protected Chopstick left;
protected Chopstick right;
protected int index;
protected int thinkTime;
protected int eatTime;
public Philosopher(Chopstick left, Chopstick right, int index) {
this.left = left;
this.right = right;
this.index = index;
}
//sleep()方法让出CPU,不释放资源。
public void thinking() throws InterruptedException{
System.out.println(this + "thinking&#