Professional Documents
Culture Documents
class P{
public static void Print(){
for(int i=0;i<DiningPhilosopher_1.Num;i++)
System.out.print(DiningPhilosopher_1.philosophers[i].Status+" ");
System.out.println("");
}
}
class Philosophers extends Thread{
/* Id of the philosopher */
private int Id;
public String Status;
/* factor of sleep time */
private int Factor=3000;
/* constructor */
public Philosophers (int x){
Id=x;
Status="IsHungry";
}
public void run(){
while(true){
/* wait for Mutex then left & right chopsticks */
DiningPhilosopher_1.Mutex.Wait();
DiningPhilosopher_1.chopstick[Id].Wait();
DiningPhilosopher_1.chopstick[(Id+1)%(DiningPhilosopher_1.Num)].Wait();
/* start of eating stage */
Status="IsEating";
P.Print();
int SleepTime=(int)(Math.random()*Factor);
try{
Thread.sleep(SleepTime);
}
catch (InterruptedException e){
System.exit(-1);
}
/* end of eating stage */
/* signals the left & right chopstick then Mutex */
DiningPhilosopher_1.chopstick[Id].Signal();
DiningPhilosopher_1.chopstick[(Id+1)%
(DiningPhilosopher_1.Num)].Signal();
Status="Thinking";
P.Print();
DiningPhilosopher_1.Mutex.Signal();
/* the philosopher is thinking now */
SleepTime=(int)(Math.random()*Factor);
try{
Thread.sleep(SleepTime);
}
catch (InterruptedException e){
System.exit(-1);
}
Status="IsHungry";
P.Print();
}
}
}