DeadlockingDiningPhilosopher.java
哲学家围着圆桌坐下,左右各有一根筷子,需要同时拥有左右筷子才能进食。
筷子是共享资源,使用和释放资源需要加锁处理。如果所有的哲学界都是先取左边的筷子,就会导致每个哲学家都有一根筷子,等待自己右边的哲学家释放筷子,从而陷入死锁的状态。
package com.test.concurrent;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class DeadlockingDiningPhilosopher {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
int ponder=10;
int size=5;
ExecutorService exec=Executors.newCachedThreadPool();
ChopStick[] sticks=new ChopStick[size];
for(int i=0;i<size;i++){
sticks[i]=new ChopStick();
}
for(int i=0;i<size;i++){
exec.execute(new Philosopher(sticks[i],sticks[(i+1)%size],i,ponder));
//此处可以通过修改最后一个哲学家取筷子的顺序来避免死锁,最后一个反序取筷子
}
TimeUnit.SECONDS.sleep(5);
exec.shutdownNow();
System.out.println("total eat count:"+Philosopher.eatcount);
}
}
class ChopStick{
private boolean taken=false;
public synchronized void take() throws InterruptedException{
while(taken){
wait();
}
taken=true;
}
public synchronized void drop(){
taken=false;
notifyAll();
}
}
class Philosopher implements Runnable{
public static int eatcount=0;
private ChopStick left;
private ChopStick right;
private final int id;
private final int ponderFactor;
private Random rand=new Random(47);
public Philosopher(ChopStick left,ChopStick right,int ident,int ponder){
id=ident;
ponderFactor=ponder;
this.left=left;
this.right=right;
}
private void pause() throws InterruptedException{
if(ponderFactor==0)
return;
TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor*250));
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(!Thread.interrupted()){
System.out.println(this+" "+"thinking ");
pause();
System.out.print(this+" grbbing right ");
right.take();
System.out.print(this+" grabbing left ");
left.take();
System.out.println(this+" is eating!!!! ");
eatcount++;
right.drop();
left.drop();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String toString(){
return "Philosopher "+id;
}
}