import java.sql.Time;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class 哲學家就餐 {
public static void main(String[] args) {
//線程池
ExecutorService exec= Executors.newCachedThreadPool();
int sum=5;
//5個筷子
Chopstick[] chopsticks=new Chopstick[sum];
for (int i = 0; i <sum ; i++) {
chopsticks[i]=new Chopstick(i);
}
//5個哲學家
for (int i = 0; i < sum-1; i++) {
exec.execute(new Philosopher(chopsticks[i],chopsticks[(i+1)%sum],i));
}
exec.execute(new Philosopher(chopsticks[0],chopsticks[sum-1],sum));
}
}
//筷子類
class Chopstick{
//筷子位置
private int index;
//狀態(有沒有被使用)
private boolean isUsed=false;
public Chopstick(int index){
this.index=index;
}
//拿筷子
public synchronized void take() throws InterruptedException {
//如果筷子被使用了,就進行等待
while (isUsed){
wait();
}
System.out.println(this+"被使用...");
isUsed=true;
}
//放筷子
public synchronized void drop(){
isUsed=false;
System.out.println(this+"被放下");
notifyAll();
}
@Override
public String toString() {
return "筷子["+index+"]";
}
}
//哲學家
class Philosopher implements Runnable{
private Chopstick left;
private Chopstick right;
//哲學家編號
private int index;
private Random rand=new Random();
public Philosopher(Chopstick left,Chopstick right,int index){
this.left=left;
this.right=right;
this.index=index;
}
@Override
public void run() {
while (!Thread.interrupted()){
try {
think();
System.out.println(this+"想吃飯。。");
eat();
} catch (InterruptedException e) {
System.out.println("InterruptedException..");
}
}
}
//思考
private void think() throws InterruptedException {
System.out.println(this+"思考");
TimeUnit.MILLISECONDS.sleep(rand.nextInt(1)*100);
}
//吃飯
private void eat() throws InterruptedException {
left.take();
right.take();
System.out.println(this+"正在吃飯。。");
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2)*100);
left.drop();
right.drop();
}
@Override
public String toString() {
return "哲學家["+index+"]";
}
}
哲學家就餐
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.