import java.util.Random;
public class Philosopher extends Thread {
enum STATES {HUNGRY, EATING, THINKING}
STATES state;
int id;
PhilosopherApplet table;
Random rand;
boolean sleep;
public Philosopher(PhilosopherApplet table, int id, boolean sleep){
state = STATES.HUNGRY;
this.id = id;
this.table = table;
this.sleep = sleep;
rand = new Random();
}
public void run(){
try {
while(true){
state = STATES.HUNGRY;
table.getFork(id, id);
table.getFork(id, (id + 1) % table.PHILOSOPHER_COUNT);
state = STATES.EATING;
if(sleep)
busyRest(rand.nextInt(2) + 1);
eat++;
table.releaseFork(id, id);
table.releaseFork(id, (id + 1) % table.PHILOSOPHER_COUNT);
state = STATES.THINKING;
if(sleep)
busyRest(rand.nextInt(2) + 1);
}
}
catch(InterruptedException ie){
ie.printStackTrace();
}
}
public String toString(){
return "Philosopher " + id + " is " + state;
}
public void busyRest(int t){
int msec = t*1000;
long time = System.currentTimeMillis();
long endTime = time + msec;
while(time < endTime){
time = System.currentTimeMillis();
}
}
private static int eat = 0;
public static synchronized int getEat(){
return eat;
}
public static synchronized void incrementEat(){
eat++;
}
}