Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – static Synchronization

Till now we have seen that synchronization can be achieved only if threads belong to the same object. But there is an exception to this rule.

Synchronization can also be achieved on a method or a block by threads belonging to different objects, but only if that method is a static synchronized and thread acquires a class monitor (lock) instead of object monitor (lock).

The static synchronized method is common for all objects of the class.

Example

 class Book
 {
     public synchronized static void read(String name)
     {
         for(int i=1;i<=5;i++)
         {
             System.out.println("I am reading "+name);
             try
             {
                 Thread.sleep(500);
             }
             catch(InterruptedException e)
             {
                 System.out.println("Exception Caught");
             }
         }
     }
 }

 class ChildThread extends Thread
 {
     Book b;
     String name;
      
     public ChildThread(Book b1,String name1)
     {
         b = b1;
         name = name1;
     }
      
     public void run()
     {
         Book.read(name);
     }
 }

 class StaticSynchroDemo
 {
     public static void main(String args[])
     {
         Book b1 = new Book();
         Book b2 = new Book();
         ChildThread t1 = new ChildThread(b1,"Java");
         ChildThread t2 = new ChildThread(b2,"C-sharp");
         t1.start();
         t2.start();
     }
 }

Output

I am reading Java
I am reading Java
I am reading Java
I am reading Java
I am reading Java
I am reading C-sharp
I am reading C-sharp
I am reading C-sharp
I am reading C-sharp
I am reading C-sharp

                                                                               OR

I am reading C-sharp
I am reading C-sharp
I am reading C-sharp
I am reading C-sharp
I am reading C-sharp
I am reading Java
I am reading Java
I am reading Java
I am reading Java
I am reading Java

 

Leave a reply