Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Synchronized Block

If we want to synchronize only the part of a method and not the complete method, then we should use synchronized block concept.

Syntax for synchronized block

 synchronized(ObjectReference)
{
    // statements
}

This block is present inside the method, to synchronize a part (a group of statements) of the method.

Example

 class Book
 {
     public void read(String lang)
     {
         for(int i = 1;i<=3;i++)
         {
             System.out.println(Thread.currentThread().getName()+" Loves Reading");
         }
         synchronized(this)
         {
             for(int i=1;i<=5;i++)
             {
                 System.out.println("I am reading "+lang);
                 try
                 {
                     Thread.sleep(100);
                 }
                 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()
     {
         b.read(name);
     }
 }

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

Output

Thread-0 Loves Reading
Thread-1 Loves Reading
Thread-0 Loves Reading
Thread-1 Loves Reading
Thread-0 Loves Reading
Thread-1 Loves Reading
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

 

Leave a reply