In this section we will discuss about Synchronization in java.

Synchronization in java with example
In this section we will discuss about Synchronization in java. Since java is a multi-threaded language so, when two or more thread used a shared resources that lead to two kind of errors: thread interference and memory consistency error, to avoid this error you need to synchronized object, that the resource will be used by one thread at a time and the process by which synchronization is achieved is called synchronization. Synchronized keyword in java create a critical section in which a lock is associated with the object . To enter the critical section a thread need to obtain the object lock. The general form of synchronized is as follows
synchronized(object)
{
statement;
}
There are two types synchronization.- Process Synchronization.
- Thread Synchronization.
There are two types of thread synchronization Mutual Exclusive and Inter-thread communication. Mutual Exclusion is achieved by making a method or a block synchronized. Mutual exclusion will keep a thread from interfering with another thread while sharing data. Synchronization is done with a lock on object means every object has a lock and if a thread need to access that object field have to acquire the lock before access them and release the lock when done. A method is synchronized using synchronized keyword.
Example : Understanding the problem without synchronization.
class Demo
{
public void print(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try { Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
}
}
}
class Threaddemo extends Thread
{
Demo d;
Threaddemo(Demo d)
{
this.d=d;
}
public void run()
{
d.print(5);
}
} class Threaddemo1 extends Thread
{
Demo d;
Threaddemo1(Demo d)
{
this.d=d;
}
public void run()
{
d.print(10);
}
}
public class Main
{
public static void main(String args[])
{
Demo d=new Demo();
Threaddemo ob1=new Threaddemo (d);
Threaddemo1 ob2=new Threaddemo1(d);
ob1.start();
ob2.start();
}
}
Output : After Compiling and executing the above program

Understanding the problem with Synchronization.
class Second
{
public synchronized void print(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try { Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
}
}
}
class Third extends Thread
{
Second d;
Third(Second d)
{
this.d=d;
}
public void run()
{
d.print(5);
}
}
class Fourth extends Thread
{
Second d;
Fourth(Second d)
{
this.d=d;
}
public void run()
{
d.print(10);
}
}
public class Main2
{
public static void main(String args[])
{
Second d=new Second();
Third ob1=new Third (d);
Fourth ob2=new Fourth(d);
ob1.start();
ob2.start();
}
}
Output : After compiling and executing the above program.
