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.