发出其他线程停止信号的更好方法? [英] Better way to signal other thread to stop?

查看:73
本文介绍了发出其他线程停止信号的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启动了几个工作线程,需要通知他们停止。由于某些线程在下一轮工作之前会休眠一段时间,因此需要一种方法即使在他们正在睡觉时也能通知他们。

Started several worker threads , need to notify them to stop. Since some of the threads will sleep for a while before next round of working, need a way which can notify them even when they are sleeping.

如果是Windows编程我可以使用事件和等待功能。在Java中我通过使用CountDownLatch对象来做到这一点,该对象的计数为1.它工作但感觉不优雅,特别是我必须检查计数值以查看是否需要退出:

If it was Windows programming I could use Event and wait functions. In Java I am doing this by using a CountDownLatch object which count is 1. It works but don't feel elegant, especially I have to check the count value to see if need to exit :

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

信号量是另一种选择,但也感觉不到非常正确。我想知道有没有更好的办法呢?谢谢。

Semaphore is another choice, but also don't feel very right. I am wondering is there any better way to do this? Thank you.

推荐答案

最佳方法是 interrupt() 工作线程。

Best approach is to interrupt() the worker thread.

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()


And as long as you have a reference to t, all that is required to "stop" t is to invoke t.interrupt().

这篇关于发出其他线程停止信号的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆