Synchronized Block in Java | Example Program

Synchronized block in Java is another way of managing the execution of threads. It is mainly used to perform synchronization on a certain block of code or statements inside the method.

Synchronizing a block of code is more powerful than synchronized method. For example, suppose there are 30 lines of code in a method, but we want to synchronize only 5 lines of code. In this case, we should use a synchronized block.

If we place all the codes of the method in the synchronized block, it will work the same as the synchronized method.

The general syntax to synchronize a block of code is as follows:

Syntax:

synchronized(object)
{
// statements or codes to be synchronized.
}

In the above syntax, object represents object reference to be locked or synchronized. The code within synchronized block is all available to only one thread at a time. They will not available to more than one thread at a time.

Once a thread has entered inside the synchronized block after acquiring lock on the specified object, other threads are blocked to wait for the object lock on the same instance.


Let’s take a simple example program to demonstrate synchronized block or statement. Look at the source code.

Program source code 1:

public class Table 
{
void printTable(int x)
{
synchronized(this) // Synchronized block.
{
for(int i = 1; i <= 3; i++)
{  
 System.out.println(x * i);  
 try
 {  
   Thread.sleep(400);  
 }
catch(InterruptedException ie)
{
 System.out.println(ie);
 }  }}
}  
}
public class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
 this.t = t;	
}
public void run()
{  
 t.printTable(2);
 }  
}
public class Thread2 extends Thread
{
Table t;
Thread2(Table t)
{
 this.t = t;	
}	
public void run()
{  
 t.printTable(10); 
 }  
}
public class SynchronizedBlock
{
public static void main(String[] args) 
{
Table t = new Table();	
Thread1 t1 = new Thread1(t);
Thread2 t2 = new Thread2(t);
 t1.start(); 
 t2.start();
 }
}
Output:
      2
      4
      6
      10
      20
      30

The code within print Table() method is not available for more than one thread simultaneously.

Hope that this tutorial has covered important points related to synchronized block in Java with example program. I hope that you will have understood this topic.
Thanks for reading!!!
Next ⇒ Inter Thread Communication in Java⇐ PrevNext ⇒