What is synchronization?

Ans

Synchronization is a keyword that is applicable only for method and blocks. Synchronization is the process of allowing threads to execute one after one.

Java support multiple threads to be executed, synchronization is a process which keep all current threads in execute to be in synch. Synchronization avoids memory consistence error caused due to inconsistent view of shared memory.

Example

class SOP
{
 public static void print(String s)
 {
 System.out.println(s+"\t"); 
 }
}
  class TestThread extends Thread
 {
 String name;
 Synchronised synchronised;
 public TestThread(String name,Synchronised synchronised)
 {
  this.synchronised=synchronised;
  this.name=name;
 start();
 }
 @Override 
 public void run() {
  // TODO Auto-generated method stub
  synchronised.test(name);
 }
}
public class Synchronised 
{
public synchronized void test(String name)
{
for(int i= 0; i<10;i++)
{
SOP.print(name+":: "+i);
try{
 Thread.sleep(500);
}
catch(Exception e)
{
 SOP.print(e.getMessage());
}
}
}
public static void main(String[] args) {
 Synchronised synchronised = new Synchronised();
 new TestThread("THREAD1", synchronised);
 new TestThread("THRED2", synchronised);
 new TestThread("thred3", synchronised);
 
}
}

====================================================================================

Output

THREAD1:: 0 
THREAD1:: 1 
THREAD1:: 2 
THREAD1:: 3 
THREAD1:: 4 
THREAD1:: 5 
THREAD1:: 6 
THREAD1:: 7 
THREAD1:: 8 
THREAD1:: 9 
thred3:: 0 
thred3:: 1 
thred3:: 2 
thred3:: 3 
thred3:: 4 
thred3:: 5 
thred3:: 6 
thred3:: 7 
thred3:: 8 
thred3:: 9 
THRED2:: 0 
THRED2:: 1 
THRED2:: 2 
THRED2:: 3 
THRED2:: 4 
THRED2:: 5 
THRED2:: 6 
THRED2:: 7 
THRED2:: 8 
THRED2:: 9