You are on page 1of 2

class Semaphore {

private int value;/*the value of semaphore*/


public Semaphore()/*Constructor*/
{
value=0;
}
public Semaphore(int i)
{
value=i;
}
/*Wait() implemented as synchronized to ensure that it is done atomically*/
public synchronized void Wait()
{
/*decremnt the semaphore*/
value--;
/*force the process to wait if value<0 */
if(value<0)
{
try
{
wait();
}
catch (InterruptedException e)
{
System.exit(-1);
}
}
}
/*Signal() is implemented as synchronized to ensure it is done atomically*/
public synchronized void Signal()
{
value++; /* increment semaphore value*/
/*wake up any waiting processes*/
if(value<=0)
notify();
}
}

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();
}
}
}

public class DiningPhilosopher_1 {


/* the number of philosophers */
public static int Num=5;
/* array of semaphores representing chopsticks */
public static Semaphore chopstick[]=new Semaphore[Num];
public static Semaphore Mutex=new Semaphore(1);
/* N philosophers */
public static Philosophers philosophers[]=new Philosophers [Num];
/* The Launch program */

public static void main(String args[]){


/* Initializing & Launching threads */
int i;
for(i=0;i<Num;i++){
chopstick[i]=new Semaphore(1);
philosophers[i]=new Philosophers(i);
philosophers[i].start();
}
System.out.println("Phil. 1 Phil. 2 Phil. 3 Phil. 4
Phil. 5");
}
}

You might also like