You are here: Home / Topics / Program to Synchronize Threads with synchronized block in Java

Program to Synchronize Threads with synchronized block in Java

Filed under: Java on 2023-10-16 06:52:24

//  Program to Synchronize Threads with synchronized block.

class Shared
{
void justDoIt( String s )
{
 System.out.println( " Starting ::: " + s );
 try
 {
  Thread.sleep( 500 );
 }
 catch( InterruptedException e ) 
 { }
 System.out.println( " Ending ::: " + s );
}
}

class MyThread extends Thread
{
Shared sr;

public MyThread( Shared sr1, String s )
{
 super( s );
 sr = sr1;
 start();
}

public void run()
{
 synchronized( sr )
 {
  sr.justDoIt( Thread.currentThread().getName() );
 }
}
}

class SynchronizedBlockDemo
{
public static void main( String args[ ] )
{
 Shared sr = new Shared();
 MyThread ob1 = new MyThread( sr, " Java" );
 MyThread ob2 = new MyThread( sr, " Programming" );
 MyThread ob3 = new MyThread( sr, " Example" );

 try
 {
  ob1.join();
  ob2.join();
  ob3.join();
 }
 catch( InterruptedException e )
 { }
}
}


Output:


Starting :::  Java
Ending :::  Java
Starting :::  Programming
Ending :::  Programming
Starting :::  Examples
Ending :::  Examples

About Author:
K
Kirti     View Profile
I am from NCR region. Follow one course until sucess.