我希望我的主线程等到多个线程中的一个发出信号\ complete。
我不需要等待所有人发出信号\结束,只有一个。
完成此类要求的最佳做法是什么?
答案 0 :(得分:3)
CountDownLatch
会做你想要的。将其初始化为1并等待。 countDown()
上的第一个线程将允许等待线程继续。
public class CountDownLatchTest
{
public static void main(String[] args) throws InterruptedException {
CountDownLatch gate = new CountDownLatch( 1 );
for( int i = 0; i < 3; i++ ) {
new Thread( new RandomWait( gate, i ) ).start();
}
gate.await();
System.out.println("Done");
}
private static class RandomWait implements Runnable
{
CountDownLatch gate;
int num;
public RandomWait( CountDownLatch gate, int num )
{
this.gate = gate;
this.num = num;
}
public void run() {
try {
Thread.sleep( (int)(Math.random() * 1000) );
System.out.println("Thread ready: "+num);
gate.countDown();
} catch( InterruptedException ex ) {
}
}
}
}
答案 1 :(得分:0)
你做这样的事情
boolean complete=false;
Object waitSync = new Object();
// the waiter has something like this
void waitFor() {
synchronized (waitSync) {
try {
while (!complete)
waitSync.wait();
} catch (Exception e) {}
}
}
// each worker calls something like this when completed
synchronized (waitSync) {
complete = true;
waitSync.notifyAll();
}
答案 2 :(得分:0)
更简单的Condition接口可以。作为额外的奖励,您可以使用 Lock.newCondition()
选择锁定CountdownLatch只能发布一次,因此可能是您想要的,也可能不是。
另请参阅:Put one thread to sleep until a condition is resolved in another thread