You are here: Home / Topics / Program to Synchronize threads with synchronize method in Java

Program to Synchronize threads with synchronize method in Java

Filed under: Java on 2023-10-16 06:51:43

//  Program to Synchronize threads with synchronize method.

class Shared
{
synchronized 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()
{
 sr.justDoIt( Thread.currentThread().getName() );
}
}

class SynchronizedMethodDemo
{
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.