Thread Synchronization

Thread Synchronization


Posted in : Core Java Posted on : November 1, 2010 at 6:16 PM Comments : [ 0 ]

This section contains the detail about the Thread Synchronization in java.

Thread Synchronization

In multithreading, situations comes where two or more threads need access to a shared resource. To avoid deadlock or errors, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this synchronization is achieved is called thread synchronization.

The general form of Synchronized statement :

synchronized(object) {
   // statements to be synchronized
}

The above block is referred to as critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object's lock. Here, object is a reference to the object being synchronized.

Given below the example which has a synchronized block within the run() method :


//This program uses a synchronized block.
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();
	}

	// synchronize calls to call()
	public void run() {
		synchronized (target) { // synchronized block
			target.call(msg);
		}
	}
}

public class ThreadSyncDemo {
	public static void main(String args[]) {
		Callme target = new Callme();
		Caller ob1 = new Caller(target, "Hello");
		Caller ob2 = new Caller(target, "Synchronized");
		Caller ob3 = new Caller(target, "World");

		// wait for threads to end
		try {
			ob1.t.join();
			ob2.t.join();
			ob3.t.join();
		} catch (InterruptedException e) {
			System.out.println("Interrupted");
		}
	}
}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>java ThreadSyncDemo
[Synchronized]
[World]
[Hello]

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics