Tuesday, April 16, 2013

Synchronization.java

class Callme
{
synchronized void call(String msg)
 {

  System.out.print("[" + msg);
   try {
    Thread.sleep(1000);
    }
   catch(Exception e){
     System.out.println("Interrupted");
    }
  System.out.println("]");
 }
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s) {
target = targ;
msg = s;
t= new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String arg[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "hello");
Caller ob2 = new Caller(target, "Syn");
Caller ob3 = new Caller(target, "he");
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(Exception e)
{
System.out.println("Interrupted");
}
}
}

2 comments: