Java唤醒睡眠线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24111441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Wake Sleeping Thread
提问by James Oravec
I did some reading of other post but didn't find an exact answer to what I'm looking for, so I hope someone can give some some clarification.
我阅读了其他帖子,但没有找到我正在寻找的确切答案,所以我希望有人能给出一些说明。
I have a program that will run for some time. I have some threads that run in the back ground that perform various tasks, to keep things simple let think of 3 threads. ThreadA
performs a task every 10 seconds, where ThreadB
does something every 30 seconds and ThreadC
does something every 5 mintues.
我有一个可以运行一段时间的程序。我有一些在后台运行的线程来执行各种任务,为了简单起见,让我们考虑 3 个线程。ThreadA
每 10 秒执行一次任务,ThreadB
每 30 秒ThreadC
执行一次,每 5 分钟执行一次。
I don't use busy waiting, and put the threads to sleep for the designated times.
我不使用忙等待,而是让线程在指定的时间内休眠。
My question is regarding a clean shut down. I have a variable that each of the threads have read access too, so they can see when the user initiates the exit of the program. The next time the threads are active, they exit their loops and join and all is good. But you can see that ThreadC only wakes up every 5 minutes.
我的问题是关于彻底关闭。我有一个变量,每个线程也具有读取访问权限,因此它们可以看到用户何时启动程序退出。下次线程处于活动状态时,它们退出循环并加入,一切都很好。但是你可以看到 ThreadC 每 5 分钟才唤醒一次。
The question I have is can I signal the sleeping threads to wake up and exit before their sleep time is over? If this is not possible, do I need to rework the code to use wait()
and notify()
or is there a better way?
我的问题是我可以在睡眠时间结束之前向睡眠线程发出信号唤醒并退出吗?如果这是不可能的,我是否需要重新编写代码才能使用wait()
,notify()
或者有更好的方法吗?
采纳答案by Patricia Shanahan
Thread.sleep
throws InterruptedException
if the thread is interrupted during the sleep. Catch that, and check your flag.
Thread.sleep
InterruptedException
如果线程在睡眠期间中断,则抛出。抓住那个,检查你的旗帜。
回答by Rod_Algonquin
You can call the interrupt()
method on your thread and will make your Thread go to running state
from block state
, but it will throw an exception which is InterruptedException
which by then you can shutdown your thread in the catch
block
您可以interrupt()
在您的线程上调用该方法并使您的 Thread 转到running state
from block state
,但它会抛出一个异常,InterruptedException
届时您可以在catch
块中关闭您的线程
Also other solution is that you can use the Timer Task that will call the run method on a certain time you specified without putting your Thread to the block state
另一种解决方案是,您可以使用 Timer Task 在您指定的某个时间调用 run 方法,而无需将您的线程置于 block state
example:
例子:
public class TimerBomb {
Toolkit toolkit;
Timer timer;
int count = 0;
public TimerBomb(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000, seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
//do stuff here
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
new TimerBomb(5);
}
});
t.start();
System.out.println("Task scheduled.");
}
}
It will run every 5 second forever.
它将永远每 5 秒运行一次。
回答by Kevin Krumwiede
If the threads are sleeping with Thread.sleep(...)
, you can wake them up with Thread.interrupt()
. Make sure you're handling the InterruptedException
and testing Thread.currentThread().isInterrupted()
in your loops.
如果线程正在休眠Thread.sleep(...)
,则可以使用 唤醒它们Thread.interrupt()
。确保您在循环中处理InterruptedException
和测试Thread.currentThread().isInterrupted()
。
回答by David Ehrmann
You should look into ExecutorService and its shutdownNow() method (which generally interrupts all the active threads). You sense reinventing the scheduling wheel.
您应该查看 ExecutorService 及其 shutdownNow() 方法(通常会中断所有活动线程)。你感觉重新发明了调度轮。
回答by Solomon Slow
All of the other answers are good answers to the question that you actually asked, but none of them gives the best answer to the question that you shouldhave asked. The question is, what's the best way to schedule several periodic tasks that must recur with different periods? The answer is, use a java.util.concurrent.ScheduledExecutorService.
所有其他答案都很好地回答了您实际提出的问题,但没有一个是您应该提出的问题的最佳答案。问题是,安排几个必须在不同时期重复出现的周期性任务的最佳方法是什么?答案是,使用 java.util.concurrent.ScheduledExecutorService。
Like all ExeuctorServices, it provides methods, shutdown() and shutdownNow(), for when you want the tasks to stop.
与所有 ExecutorServices 一样,它提供了 shutdown() 和 shutdownNow() 方法,用于您希望任务停止的时间。