Home > Java > Java Program to handle Thread Synchronization by using synchronized object – Q30

Java Program to handle Thread Synchronization by using synchronized object – Q30

January 15, 2009 Leave a comment Go to comments

Q30: Java Program to synchronize methods through synchronizing object

class Callme{
	void call(String msg){
		System.out.print("[" + msg);
		try{
			Thread.sleep(1000);
		}
		catch(InterruptedException 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(){
		synchronized(target){
			target.call(msg);
		}
	}
}

class Synch1{
	public static void main(String args[]){
		Callme target = new Callme();
		Caller ob1 = new Caller(target, "Hello");
		Caller ob2 = new Caller(target, "Dear");
		Caller ob3 = new Caller(target, "Manoj");
		try{
			ob1.t.join();
			ob2.t.join();
			ob3.t.join();
		}
		catch(InterruptedException e){
			System.out.println("Interrupted");
		}
	}
}

… from College notes (BCA/MCA assignments):


  1. No comments yet.
  1. No trackbacks yet.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.