我有一个线程,不时更新它的状态,我希望第二个线程能够等待第一个线程完成.像这样的东西:
Thread 1:
while(true) {
...do something...
foo.notifyAll()
...wait for some condition that might never happen...
...
}
Thread 2:
...
foo.wait();
...
Run Code Online (Sandbox Code Playgroud)
现在这看起来不错,除非线程1的notifyAll()在线程2的wait()之前运行,在这种情况下,线程2等待直到线程1 再次通知(这可能永远不会发生).
我的解决方案:
a)我可以使用CountDownLatch或Future,但两者都存在问题,即它们本身只运行一次.也就是说,在Thread 1的while循环中,我需要创建一个新的foo来等待每次,而Thread 2需要询问哪个foo等待.我对简单的写作感觉不好
while(true) {
foo = new FutureTask();
...
foo.set(...);
...wait for a condition that might never be set...
...
}
Run Code Online (Sandbox Code Playgroud)
因为我担心在foo = new FutureTask()时,当有人等待旧的foo时会发生什么(因为"某种原因",set没有被调用,例如异常处理中的错误)?
b)或者我可以使用信号量:
class Event {
Semaphore sem;
Event() { sem = new Semaphore(1); sem . }
void signal() { sem.release(); }
void reset() { sem.acquire(1); } …Run Code Online (Sandbox Code Playgroud)