我有一个线程必须等待来自不同线程的多个对象。
@Override
public void run() {
while (true) {
for (BackgroundTask task : tasks) {
synchronized (task) {
if (task.isReady()) {
task.doTask();
}
}
}
}
}
但这是对 CPU 时间的愚蠢使用。 如何等待多个对象?
最佳答案
海事组织CountDownLatch将是解决它的好方法。引用自 Javadoc:
class Driver2 { // ...
void main() throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(N);
Executor e = ...
for (int i = 0; i < N; ++i) // create and start threads
e.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
}
}
class WorkerRunnable implements Runnable {
private final CountDownLatch doneSignal;
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
public void run() {
try {
doWork(i);
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
}
void doWork() { ... }
}
关于java - 如何等待多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5460103/