Synchronization in Java Thread

What is Synchronization?

Synchronization is the process of allowing threads to execute one after another. It provides the control to access multiple threads to shared resources.  

Java supports multiple threads to be executed. Without synchronization, one thread can modify a shared variable while another thread can update the same shared variable, which can lead to significant error.

When a method is declared as synchronized, the threads hold the monitor for that thread object. If any thread uses synchronized method then other threads are blocked until that thread releases the monitor.

Synchronization Block

It can be used to achieve synchronization on a specific resource of method. Scope of the method is more than the synchronization block.

Syntax:
synchronized
{
       // code
}

Example : Working of synchronization block

class SynchDemo
{  
     void printNumber(int n)
     {  
          synchronized(this)
          {
               for(int i=1;i<=5;i++)
               {  
                    System.out.println(n+" * "+i+" = "+n*i);  
                    try
                    {  
                           Thread.sleep(400);  
                    }
                    catch(Exception e)
                    {
                           System.out.println(e);
                    }  
               }  
          }  
     }
}
class MainThread1 extends Thread
{  
       SynchDemo t;  
       MainThread1(SynchDemo t)
       {
              this.t=t;  
       }  
       public void run()
       {
              t.printNumber(4);  
       }  
}  
class MainThread2 extends Thread
{  
       SynchDemo t;  
       MainThread2(SynchDemo t)
       {  
              this.t=t;  
       }
       public void run()
       {
              t.printNumber(10);  
       }
}  
public class TestSynchronizedBlock
{  
       public static void main(String args[])
       {  
              SynchDemo obj = new SynchDemo();  
              MainThread1 t1=new MainThread1(obj);
              MainThread2 t2=new MainThread2(obj);  
              t1.start();  
              t2.start();  
       }  
}


Output:
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50