我正在實現以下Java接口以允許線程暫停和恢復。我有一個使用wait()/ notifyAll()的工作版本,但我想知道是否有更簡單的方法來執行它(例如,在java.util.concurrent中使用一些漂亮的小部件)?避免在實用程序中等待/通知掛起/恢復線程
public interface Suspender {
/**
* Go into pause mode: any threads which subsequently call maybePause()
* will block. Calling pause() if already in pause mode has no effect.
*/
void pause();
/**
* Leave pause mode: any threads which call maybePause() will not block,
* and any currently paused threads will be unblocked. Calling resume()
* if not in pause mode has no effect.
*/
void resume();
/**
* If the Suspender is in pause mode, block, and only resume execution
* when the Suspender is resumed. Otherwise, do nothing.
*/
void maybePause();
}
總是值得關注一個問題的不同方法,但Suspender接口對我的用例非常適用。我更感興趣的是如何實現該接口而不訴諸低級別的併發原語。 –