Write a program in Java to demonstrate use of synchronization of threads when multiple threads are trying to update common variable.
AIM: Write a program in Java to demonstrate the use of synchronization of threads when multiple threads are trying to update common variables.
CODE:
class Test{
void call(String msg){
System.out.print("\n["+msg);
try{
Thread.sleep(100);
}
catch(InterruptedException e){
System.out.println(e);
}
System.out.println("]");
}
}
class demoThread extends
Thread{
Test c;
String msg;
demoThread(Test c, String msg){
this.c=c;
this.msg=msg;
}
public void run(){
synchronized(c){
c.call(msg);
}
}
}
class p32{
public static void main(String args[]){
Test c = new Test();
demoThread dt1 = new
demoThread(c,"Hiii");
System.out.println("\ndemoThread 1: "+dt1);
demoThread dt2 = new
demoThread(c,"Hello");
System.out.println("\ndemoThread 2: "+dt2);
demoThread dt3 = new demoThread(c,"World!!");
System.out.println("\ndemoThread 3: "+dt3);
dt1.start();
dt2.start();
dt3.start();
}
}
OUTPUT:
Comments
Post a Comment