Advertisements
Home > Java > Java Program to show Thread Synchronization – Q28

Java Program to show Thread Synchronization – Q28


Q28: Java Program to show that if three threads are of equal priority and they are not synchronized then more than one thread may be executing in single function which give wrong values. Output ([hello[dear[bhaskar]]]).

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(){
		target.call(msg);
	}
}

class Synch{
	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):


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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: