发出其他线程停止信号的更好方法?
启动了几个工作线程,需要通知他们停止。 由于某些线程在下一轮工作之前会hibernate一段时间,因此需要一种即使在睡觉时也可以通知它们的方法。
如果是Windows编程,我可以使用Event和wait函数。 在Java中我通过使用CountDownLatch对象来做到这一点,该对象的计数为1.它工作但感觉不优雅,特别是我必须检查计数值以查看是否需要退出:
run(){ while(countDownLatch.count()>0){ //working // ... countDownLatch.wait(60,TimeUnit.SECONDS); } }
信号量是另一种选择,但也感觉不对。 我想知道有没有更好的方法呢? 谢谢。
最好的方法是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()
。
使用内置线程中断框架。 要停止工作线程调用workerThread.interrupt()
这将导致某些方法(如Thread.sleep())抛出一个中断的exception。 如果您的线程没有调用可中断的方法,那么您需要检查中断的状态。
在工作线程中:
run() { try { while(true) { //do some work Thread.sleep(60000); } } catch(InterruptedException e) { //told to stop working } }
好的方法是interrupt()
线程,并在内部线程make循环之类
try { while (!Thread.interrupted()) { ... } } catch (InterruptedException e) { // if interrupted in sleep }
请记住中断时的两种情况:
- 如果你
sleep
或wait
那么将抛出InterruptedException
; - 在其他情况下,将为您自己检查的线程设置中断标志。
要拥有一个线程池,我会使用ExecutorService或ScheduledExecutorService来执行延迟/定期任务。
当你希望工人停下来时你可以使用
executorService.shutdown();
另一种最好的方法是使用interrupt( )
方法。
例如,以下是线程如何使用此信息来确定它是否应该终止:
public class TestAgain extends Thread { // ... // ... public void run( ) { while (!isInterrupted( )) { // ... } } }