class ChopStick{
boolean available;
ChopStick(){
available=true;
}
public synchronized void takeup(){
while(!available){
try
{
System.out.println("Hello is waiting for the other chopStick");
wait();
}
catch(InterruptedException e){}
}
available=false;
}
public synchronized void putdown(){
available=true;
notify();
}
}
class Hello extends Thread{
ChopStick left,right;
int hello_num;
Hello(int num,ChopStick chop1,ChopStick chop2){
hello_num=num;
left=chop1;
right=chop2;
}
public void eat(){
left.takeup();
right.takeup();
System.out.println("Hello "+(hello_num+1)+" is eating");
}
public void think(){
left.putdown();
right.putdown();
System.out.println("Hello "+(hello_num+1)+" is THinking");
}
public void run(){
while(true){
eat();
try
{
sleep(1000);
}
catch(InterruptedException ex){}
think();
try
{
sleep(1000);
}
catch(InterruptedException ex){}
}
}
}
class ThreadAllDemo{
static ChopStick[] chopsticks=new ChopStick[5];
static Hello[] hellos=new Hello[5];
public static void main(String a[]){
for(int count=0;count<=4;count++){
chopsticks[count]=new ChopStick();
}
for(int count=0;count<=4;count++){
hellos[count]=new Hello(count,chopsticks[count],chopsticks[(count+1)%5]);
}
for(int count=0;count<=4;count++){
hellos[count].start();
}
}
}
No comments:
Post a Comment