Skip to main content


Showing posts from October, 2008

Thread Synchronization using synchronized blocks

In the previous example the Shared class provides synchronized method for threads. Threads do nothing so if share class removes the synchronized then thread object will not be able to access the print method synchronously.             There is second mechanism by which the thread can provided the synchronization to the any object or block. class  MyThread1  extends   Thread {         Shared s;     MyThread1(Shared s)     {          this .s = s;     }          public   void  run()     {              synchronized (s)         {             s.print();         }     } } class  MyThread2  extends   Thread {         Shared s;     MyThread2(Shared s)     {          this .s = s;     }          public   void  run()     {              synchronized (s)         {             s.print();         }     } } class  syn {      public   static   void  main( String  ar[])     {         Shared obj = new  Shared();         MyThread1 t1 = new  MyThread1(obj);         MyT

Thread Synchronization

The mechanism to accomplish the mutual access of shared resource for two or more thread is referred as the synchronization .when two or more thread access single resource then it is ensured that only one thread should access it at a time. The core concept of synchronization is the monitor. Only one thread can get the access to monitor at a time or we can say only one thread can enter in the monitor at a time. If one thread using the shared resource than it is said to be in the monitor and it acquires the lock on the monitor so no anther thread has the permission to access the shared recourse. When first thread finishes its execution then it release the lock from the monitor and frees the monitor to use by another thread. In the java all the object have their implicit monitor. So it is easy to synchronize any object or any method of object. There are two ways in which execution of code can be synchronized: ·          synchronized methods ·          synchronized blocks synchronized met