Share on Google+Share on Google+

Java :Thread Synchronization

This section explains how to use concept of synchronization in java Thread.

Java :Thread Synchronization

This section explains how to use concept of synchronization in java Thread.

Thread Synchronization : .

Java supports multi-threading concept that is multiple threads run parallel to complete the execution of program. So for the multi-threaded application, synchronization of java class is necessary. You can use "synchronized" keyword to use  synchronization concept in your java application.
When we are running two or more thread which want to access shared resource, It is necessary to confirm that at a time one thread would be able to use the resource. To overcome this problem java provides concept of Synchronization.

There are two way to use synchronization - synchronized methods and synchronized statements.

Syntax of synchronized method -

synchronized methodName(arguments) {
// statements

Syntax of synchronized statement -

synchronized(object) {
// statements to be synchronized

Example :  In this example we are synchronizing method.

class Sync extends Thread{
  static String msg[]={"This", "is", "a", "synchronized", "variable"};
  Sync(String threadname){
  public void run(){
  public synchronized void display(String threadN){
  for(int i=0;i<5;i++)
  }catch(Exception e){}
public class ThreadSynchronized {
  public static void main(String[] args) {
	  Sync t1=new Sync("Thread 1 : ");
  Sync t2=new Sync("Thread 2 : ");

Output :

Thread 1 : is
Thread 1 : a
Thread 1 : synchronized
Thread 1 : variable
Thread 2 : This
Thread 2 : is
Thread 2 : a
Thread 2 : synchronized
Thread 2 : variable


Posted on: November 5, 2012 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.


Advertisement null