【发布时间】:2016-03-31 03:00:36
【问题描述】:
我希望我的主线程等到许多线程中的一个发出信号\完成。
我不需要等待所有人发出信号\完成,只需一个。
实现此类要求的最佳做法是什么?
【问题讨论】:
-
添加一些关于如何创建线程的代码,例如由一个执行程序创建的所有线程或多个执行程序创建线程.. 只给出线程创建的骨架
-
使用lock
标签: java multithreading
我希望我的主线程等到许多线程中的一个发出信号\完成。
我不需要等待所有人发出信号\完成,只需一个。
实现此类要求的最佳做法是什么?
【问题讨论】:
标签: java multithreading
更简单的Condition 接口就可以了。作为额外的奖励,您可以使用 Lock.newCondition()
选择您的锁CountdownLatch 只能被释放一次,所以这可能是也可能不是你想要的。
另见:Put one thread to sleep until a condition is resolved in another thread
【讨论】:
你做这样的事情
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();
}
【讨论】:
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 ) {
}
}
}
}
【讨论】: