class DemoOne{
void display(int num){
System.out.println(""+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("Done");
}
}
class DemoTwo implements Runnable{
int number;
DemoOne objone;
Thread objTh;
public DemoTwo(DemoOne one_num,int num){
objone=one_num;
number=num;
objTh=new Thread(this);
objTh.start();
}
public void run(){
synchronized(objone){
objone.display(number);
}
}
}
class SynchBlock{
public static void main(String a[]){
DemoOne objone=new DemoOne();
int digit=10;
DemoTwo objSynch1=new DemoTwo(objone,digit++);
DemoTwo objSynch2=new DemoTwo(objone,digit++);
DemoTwo objSynch3=new DemoTwo(objone,digit++);
try
{//wait for Threads to end
objSynch1.objTh.join();
objSynch2.objTh.join();
objSynch3.objTh.join();
}
catch(InterruptedException ex){
System.out.println("Error : "+ex);
}
}
}
No comments:
Post a Comment