Share on Google+Share on Google+

Thread Synchronization in Java

In this section, you will learn Thread Synchronization in Java

Thread Synchronization in Java

Sometimes, when two or more threads need shared resource, they need a proper mechanism to ensure that the resource will be used by only one thread at a time.

The mechanism we use to achieve this is known as thread synchronization.

The thread synchronization is achieved through the synchronized keyword. The statements which need to be synchronized should put into the synchronized block It is also known as critical section. The synchronized block is defined as follows :

synchronized(object) {
   // statements to be synchronized

Object in Java which have synchronization block(critical section) gets a lock related with the object. To get access to the critical section or synchronization block you need the associated object's lock.


Given below the example using a synchronized block having thread synchronization :

class Print {
void call(String msg) {
System.out.print("[" + msg);
try {
} catch (InterruptedException e) {

class PrintCaller implements Runnable {
String msg;
Print target;
Thread t;

public PrintCaller(Print targ, String s) {
target = targ;
msg = s;
t = new Thread(this);

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

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

// wait for threads to end
try {
} catch (InterruptedException e) {





Download Source Code


Posted on: July 22, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Thread Synchronization in Java  

Post your Comment

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