Java :Thread Synchronization


 

Java :Thread Synchronization

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

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){
  super(threadname);
  }
  public void run(){
  display(getName());
  }
  public synchronized void display(String threadN){
  for(int i=0;i<5;i++)
  System.out.println(threadN+msg[i]);
  try{
  this.sleep(1000);
  }catch(Exception e){}
  }
}
public class ThreadSynchronized {
  public static void main(String[] args) {
	  Sync t1=new Sync("Thread 1 : ");
  t1.start();
  Sync t2=new Sync("Thread 2 : ");
  t2.start();
  
}
}

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

Ads