2011-07-28 46 views
9

啓動了多個工作線程,需要通知他們停止。由於某些線程在下一輪工作之前會休眠一段時間,因此需要一種即使在睡覺時也能通知它們的方式。更好的方式來通知其他線程停止?

如果是Windows編程,我可以使用事件和等待功能。在Java中,我使用的CountDownLatch對象,指望這樣做是1。它的工作原理,但並不感到優雅,尤其是我要檢查計數值,看看是否需要退出:

run(){ 
    while(countDownLatch.count()>0){ 
      //working 
      // ... 
      countDownLatch.wait(60,TimeUnit.SECONDS); 
    } 
} 

信號燈是另一個選擇,但也不覺得很正確。我想知道有沒有更好的方法來做到這一點?謝謝。

+1

這是不太你正在尋找的答案,但你應該使用線程池(java.util.concurrent中)。我幾乎可以肯定他們可以做你想做的事情,而且他們沒有bug,你可以利用你的時間來開發其他事情。 – toto2

+0

你想停止所有的線程,還是隻想停止一些? – Moonbeam

+1

@Moonbeam我需要單獨阻止它們,所以線程池似乎不是一個可行的解決方案。 – HourseArmor

回答

7

最好的辦法是interrupt()工作者線程。


Thread t = new Thread(new Runnable(){ 
    @Override 
    public void run(){ 
     while(!Thread.currentThread().isInterrupted()){ 
      //do stuff 
      try{ 
       Thread.sleep(TIME_TO_SLEEP); 
      }catch(InterruptedException e){ 
       Thread.currentThread().interrupt(); //propagate interrupt 
      } 
     } 
    } 
}); 
t.start(); 

而且只要你有t參考,所有需要「停止」 t是調用t.interrupt()

+4

我喜歡你提到的中斷標誌被清除後再次中斷的事實。 –

0

使用內置線程中斷框架。要停止工作線程調用workerThread.interrupt(),這將導致某些方法(如Thread.sleep())拋出一箇中斷的異常。如果你的線程沒有調用可中斷的方法,那麼你需要檢查中斷狀態。

在工作線程:

run() { 
    try { 
     while(true) { 
      //do some work 
      Thread.sleep(60000); 
     } 
    } 
    catch(InterruptedException e) { 
     //told to stop working 
    } 
} 
0

好辦法是interrupt()線程,內螺紋化妝週期一樣

try { 
    while (!Thread.interrupted()) { 
     ... 
    } 
} catch (InterruptedException e) { 
    // if interrupted in sleep 
} 

記住這兩種情況下執行中斷時:

  • 如果您sleepwait那麼InterruptedException會被拋出;
  • 在其他情況下,將爲您必須檢查自己的線程設置中斷標誌。
0

其他最好的方法是使用interrupt()方法。

E.g這裏有一個線程如何使用這些信息來確定它是否應該終止:

public class TestAgain extends Thread { 
      // ... 
      // ... 
     public void run() { 
       while (!isInterrupted()) { 
        // ... 
        } 
       }  
      } 
0

要有一個線程池我會用ExecutorService或延遲/週期性任務ScheduledExecutorService

當你需要的工人停止,您可以使用

executorService.shutdown(); 
+0

他不得不使用shutdownNow()。 – kervin

相關問題