by Dinesh Thakur

When two or more threads wants to access a shared resource, then it must ensure that the resource will be used by only one thread at an instant of time. The mechanism of this process is called synchronization. Synchronization is the concept of the monitor or semaphore. Monitor works as mutex and restrict to one thread to own a monitor at a given time. As the thread acquires the lock, all the threads that want to acquire the monitor will be suspended. As the first thread exits from the monitor, one thread will acquire monitor from the waiting list of threads.

Synchronization of code can be in two ways, but both use synchronized keyword.

 

  1. Using synchronized method
  2. Using synchronized statement

 

Example:

 

public class SynchronizedMethod extends Object

{

         private static int c = 1;

         private static void print (String msg)

           {

                String threadName = Thread.currentThread().getName();

                System.out.println(threadName + ": " + msg);

           }

               public static synchronized int getCount()

               {

                    int i = c;

                    c++;

                    return i;

               }

                public static void main(String[] args)

             {

                   try

                    {

                        Runnable runnable = new Runnable()

                         {

                                public void run()

                             {

                                   System.out.println("count=" + getCount());

                              }

                          };

                                  Thread thread1 = new Thread(runnable, "Threadl");

                                   thread1.start();

                                  Thread.sleep(500);

                                  Thread thread2 = new Thread(runnable, "Thread2");

                                   thread2.start();

                                  Thread.sleep(500);

                                  Thread thread3 = new Thread(runnable, "Thread3");

                                   thread3.start();

                                   Thread.sleep(500);

                                   Thread thread4 = new Thread(runnable, "Thread4");

                                    thread4.start();

                      }

                                    catch(Exception x ) {}

             }

}

Output

Synchronized