位置:首页 > Java技术 > java实例在线教程 > Java如何暂停线程?

Java如何暂停线程?

如何暂停一个线程一会儿?

解决方法

下面的示例演示如何通过创建sleepingThread()方法来暂停一个线程一段时间。

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.");
   }
}

结果

上面的代码示例将产生以下结果。

The thread has been suspened.