/**
* Created by Panda on 2018/6/6.
*/publicclassChopstick {privateboolean taken=false;
publicsynchronizedvoidtake() throws InterruptedException{
while (taken)
wait();
taken=true;
}
publicsynchronizedvoiddrop(){
taken=false;
notifyAll();
}
}
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Created by Panda on 2018/6/6.
*/publicclassPhilosopherimplementsRunnable {private Chopstick left;
private Chopstick right;
privatefinalint id;
privatefinalint ponderFactor;
private Random random = new Random(47);
publicPhilosopher(Chopstick left, Chopstick right, int id, int ponderFactor) {
this.left = left;
this.right = right;
this.id = id;
this.ponderFactor = ponderFactor;
}
privatevoidpause() throws InterruptedException{
if(ponderFactor==0) return;
TimeUnit.MILLISECONDS.sleep(random.nextInt(ponderFactor*250));
}
@Overridepublicvoidrun() {
try{
while (!Thread.interrupted()){
System.out.println(this+" "+"thinking");
pause();
System.out.println(this+" "+"grabbing right");
right.take();
System.out.println(this+" "+"grabbing left");
left.take();
System.out.println(this+" "+"eating");
pause();
right.drop();
left.drop();
}
}catch (InterruptedException e){
System.out.println(this+" "+"exiting vis interrupt");
}
}
public String toString(){return"Philosopher "+id;}
}