[英]Thread suspend and resume inside run()
我通過實現runnable
和重寫run()
實現多線程。 我想將線程掛在run()
。
請幫我
我應該在void run(){ }
什么?
不知道更多細節就很難說出來。 但是您的選擇是:
Thread.sleep()
-無條件睡眠一會兒
wait/notify
對以等待某個對象
阻止諸如BlockingQueue
類的數據結構,當集合中出現某些內容時喚醒線程
Thread.join()
等待其他線程
Java 5並發抽象,例如Semaphore
, CountDownLatch
, CyclicBarrier
等
這樣做的通常方法是在某個對象上調用wait
,然后另一個線程可以通知該對象。 這將是您的代碼的模式:
public void run() {
. . .
// decide to suspend thread execution:
synchronized (LOCK) {
try {
LOCK.wait();
} catch (InterruptedException e) {
// thread was interrupted -- time to return?
}
}
// execution resumes here after interrupt or notify
}
然后其他一些線程執行以下代碼:
synchronized (LOCK) {
LOCK.notify(); // or notifyAll();
}
在這些代碼段中, LOCK
是兩個代碼段都可以訪問的對象。 如果可以使用可用的對象來完成這項工作,則不需要單獨的對象。
您可能需要Object.wait()
然后是Object.notifyAll()
,但是正確使用它是一件棘手的事情。 繼續閱讀。 Josh Bloch的有效Java是一個很好的來源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.