You are here: Home / Topics / Program to use suspend( ) and resume( ) method in Java

Program to use suspend( ) and resume( ) method in Java

Filed under: Java on 2023-10-16 06:48:35

// Program to use suspend( ) and resume( ) method.

class NewThread implements Runnable
{
String tn;
Thread t;

NewThread( String tname )
{
 tn = tname;
 t = new Thread( this, tn );
 System.out.println( " New Thread ::: " + t );
 t.start();
}

public void run()
{
 try
 {
  for( int i=1 ; i<=10 ; i++ )
  {
   System.out.println( tn + " ::: " + i );
   Thread.sleep( 200 );
  }
 }
 catch( InterruptedException e )
 {  }
 System.out.println( tn + " Finishing ... " );
}
}

public class SuspendResumeDemo 
{
public static void main( String args[ ] )
{
 NewThread ob1 = new NewThread( "ONE" );
 NewThread ob2 = new NewThread( "TWO" );
 try
 {
  Thread.sleep( 500 );
  ob1.t.suspend();
  System.out.println( " Thread ONE is Suspended." );
  Thread.sleep( 500 );
  ob1.t.resume();
  System.out.println( " Thread ONE is Resumed." );
  Thread.sleep( 500 );
  ob2.t.suspend();
  System.out.println( " Thread TWO is Suspended." );
  Thread.sleep( 500 );
  ob2.t.resume();
  System.out.println( " Thread TWO is Resumed." );

  System.out.println( " Waiting for threads to finish." );  
  ob1.t.join();
  ob2.t.join();
 }
 catch( InterruptedException e )
 {  }
 System.out.println( " Finishing Main Thread." );
   }
}

 

Output:

 New Thread ::: Thread[ONE,5,main]
 New Thread ::: Thread[TWO,5,main]
ONE ::: 1
TWO ::: 1
ONE ::: 2
TWO ::: 2
ONE ::: 3
TWO ::: 3
 Thread ONE is Suspended.
TWO ::: 4
TWO ::: 5
 Thread ONE is Resumed.
ONE ::: 4
TWO ::: 6
ONE ::: 5
TWO ::: 7
ONE ::: 6
TWO ::: 8
 Thread TWO is Suspended.
ONE ::: 7
ONE ::: 8
 Thread TWO is Resumed.
 Waiting for threads to finish.
TWO ::: 9
ONE ::: 9
TWO ::: 10
ONE ::: 10
TWO Finishing ...
ONE Finishing ...
 Finishing Main Thread.


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