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;
}
}
通过模拟经典的哲学家就餐问题,展示并发编程中死锁的现象。五个哲学家围坐在圆桌旁,每位哲学家左右各有一根筷子,必须同时拿到两根筷子才能吃饭。若所有哲学家遵循相同取筷顺序,则会导致死锁状态。
2037

被折叠的 条评论
为什么被折叠?



