Synchronization


Synchronization

Asynchronous behavior is introduced to the programs in multithreading. If a thread is writing some data and a second thread may be reading the same data at that time. This leads to inconsistency of the data. When multiple threads share the same resource, a way should be found out so that only one thread can use the resource at a time. The procedure which can be used is called as synchronization. Synchronized methods are provided in java to implement synchronized behavior. Once a thread reaches inside a synchronized method, no thread can use the same object to call any other synchronized method. Remaining threads have to wait till the first thread comes out of the synchronized block. There are two types of synchronization namely process synchronization and thread synchronization. Thread synchronization is further divided into two types: mutual exclusive and inter thread communication. Mutual exclusive is of three types: synchronized method, synchronized block and static synchronizion.

Syntax:

Synchronized (obj)
{
//statements which have to be synchronized
}

2) Implementing the Runnable Interface

A new class is created which implements java.lang.Runnable interface and overrides run() method. A Thread object can be instantiated and call start() method on this object.

Example:

Com.knowledge2life class Table{ synchronized void printTable(int n){ for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } public class Main{ public static void main(String args[]){ final Table obj = new Table(); Thread t1=new Thread(){ public void run(){ obj.printTable(5); } }; Thread t2=new Thread(){ public void run(){ obj.printTable(100); } }; t1.start(); t2.start(); } }

OUTPUT:

5
10
15
20
25
100
200
300
400
500