问题描述
我正在研究java中的多线程游戏。我有几个工作线程从中央线程管理器获取模块,然后中心线程管理器自己执行它。现在我希望能暂停这样一个线程,如果暂时没有任何东西可以执行。我已经尝试从线程管理器调用它上面的wait()方法,但这只会导致它忽略它后面的notify()调用。
I am working on a multithreaded game in java. I have several worker threads that fetch modules from a central thread manager, which then executes it on its own. Now I would like to be able to pause such a thread if it temporarily has nothing to execute. I have tried calling the wait() method on it from the thread manager, but that only resulted in it ignoring the notify() call that followed it.
我google了一个也就是说,只发现大多数网站引用了诸如suspend(),pause()等函数,这些函数现在在java文档页面上被标记为已弃用。
I googled a bit on it too, only finding that most sites refer to functions like suspend(), pause(), etc, which are now marked a deprecated on the java documentation pages.
所以一般来说,按需暂停或继续线程的方法是什么?
So in general, what is the way to pause or continue a thread on demand?
推荐答案
你可以使用if块如果要暂停线程的操作,则具有sentinal变量的线程设置为false。如果线程正在执行循环,这种方法效果最好。
You can use an if block in the thread with a sentinal variable that is set to false if you want to halt the thread's action. This works best if the thread is performing loops.
这篇关于如何按需挂起java线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!