Suspend một thread trong Java



Miêu tả vấn đề

Cách suspend một thread trong Java?

Giải pháp

Ví dụ sau minh họa cách suspend một thread bằng việc tạo phương thức sleepingThread() trong Java.

public class SleepingThread extends Thread {
   private int countDown = 5;
   private static int threadCount = 0;
   public SleepingThread() {
      super("" + ++threadCount);
      start();
   }
   public String toString() { 
      return "#" + getName() + ": " + countDown;
   }
   public void run() {
      while (true) {
         System.out.println(this);
         if (--countDown == 0)
         return;
         try {
            sleep(100);
         }
         catch (InterruptedException e) {
            throw new RuntimeException(e);
         }
      }
   }
   public static void main(String[] args) 
   throws InterruptedException {
      for (int i = 0; i < 5; i++)
      new SleepingThread().join();
      System.out.println("The thread has been suspened.");
   }
}

Kết quả

Code trên sẽ cho kết quả sau:

The thread has been suspened.

thread_trong_java.jsp