Java唤醒唤醒线程 [英] Java Wake Sleeping Thread

查看:96
本文介绍了Java唤醒唤醒线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了其他文章,但没有找到我想要的确切答案,所以我希望有人可以澄清一下.

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.

我有一个程序,它将运行一段时间.我有一些后台运行的线程来执行各种任务,为使事情简单,让我们考虑3个线程. ThreadA每10秒执行一次任务,其中ThreadB每30秒执行一次任务,ThreadC每5分钟执行一次任务.

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.

我不使用忙碌的等待,而是在指定的时间使线程进入睡眠状态.

I don't use busy waiting, and put the threads to sleep for the designated times.

我的问题是关于彻底关闭.我有一个变量,每个线程也具有读取权限,因此它们可以看到用户何时启动程序退出.下次线程活动时,它们退出循环并加入,一切都很好.但是您可以看到ThreadC仅每5分钟唤醒一次.

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.

我的问题是,我可以在睡眠时间结束之前发信号通知睡眠线程唤醒并退出吗?如果不可能,是否需要重新编写代码以使用wait()notify()还是有更好的方法?

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?

推荐答案

Thread.sleep抛出InterruptedException.赶上,然后检查您的标志.

Thread.sleep throws InterruptedException if the thread is interrupted during the sleep. Catch that, and check your flag.

这篇关于Java唤醒唤醒线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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