Example: Suspend a thread using Java

This example shows a Java™ program suspending an actively running thread.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*
FileName: ATEST14.java
 
The output of this example is as follows:
 Entered the testcase
 Create a thread
 Start the thread
 Wait a bit until we 'realize' the thread needs to be suspended
 Thread: Entered
 Thread: Active processing
 Thread: Active processing
 Suspend the thread
 Wait a bit until we 'realize' the thread needs to be resumed
 Resume the thread
 Thread: Active processing
 Wait for the thread to complete
 Thread: Active processing
 Thread: Active processing
 Thread: Completed
 Testcase completed
*/
import java.lang.*;
 
 
public class ATEST14 {
 
   static class theThread extends Thread {
      public void run() {
         int        loop=6;
         System.out.print("Thread: Entered\n");
         while (--loop > 0) {
            System.out.print("Thread: Active processing\n");
            safeSleep(1000, "Thread: sleep interrupted\n");
         }
         System.out.print("Thread: Completed\n");
      }
   }
 
   public static void main(String argv[]) {
      System.out.print("Entered the testcase\n");
 
      System.out.print("Create a thread\n");
      theThread t = new theThread();
 
      System.out.print("Start the thread\n");
      t.start();
 
      System.out.print("Wait a bit until we 'realize' the thread needs to be suspended\n");
      safeSleep(2000, "Main first sleep interrupted\n");
      System.out.print("Suspend the thread\n");
      t.suspend();
 
      System.out.print("Wait a bit until we 'realize' the thread needs to be resumed\n");
      safeSleep(2000, "Main second sleep interrupted\n");
      System.out.print("Resume the thread\n");
      t.resume();
 
      System.out.print("Wait for the thread to complete\n");
      try {
         t.join();
      }
      catch (InterruptedException e) {
         System.out.print("Join interrupted\n");
      }
 
      System.out.print("Testcase completed\n");
      System.exit(0);
   }
 
   public static void safeSleep(long milliseconds, String s) {
      try {
         Thread.sleep(milliseconds);
      }
      catch (InterruptedException e) {
         System.out.print(s);
      }
   }
 
}