如何使线程从Java中的另一个线程休眠 [英] How to make a thread sleep from another thread in Java
问题描述
我应该采取什么样的方法在Java中执行此操作? p>
IMHO的干净方法是让Thread1定期轮询一些状态变量,看看是否被要求暂停。如果被要求暂停,那么它应该暂停它的执行,等待一些锁被释放。 Thread2应该通过更改共享状态变量的值来暂停,然后等待Thread1接受暂停请求,然后执行其动作并释放锁定Thread1正在等待。
简而言之,两个线程必须协作。没有办法,我知道如果没有协作,就能干净地暂停线程。
I have two threads of execution(say Thread1 and Thread2). Thread2 is listening for a particular event and as the event occurs it wants to stop execution of Thread1 and trigger an action. After it is done with the action it needs to continue the execution of Thread1 from where it stopped.
What kind of approach should I take to do this in Java?
The clean way to do it, IMHO, is to make Thread1 regularly poll some state variable to see if it has been asked to pause. If it's been asked to pause, then it should suspend its execution, waiting for some lock to be released.
Thread2 should ask Thread1 to pause by changing the value of the shared state variable, then potentialy wait for Thread1 to accept the pause request, then execute its action and release the lock on which Thread1 is waiting.
In short, the two threads must collaborate. There is no way that I'm aware of to pause a thread cleanly without its collaboration.
这篇关于如何使线程从Java中的另一个线程休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!