I开发者_StackOverflow have a thread which must wait several objects from different threads.
@Override
public void run() {
while (true) {
for (BackgroundTask task : tasks) {
synchronized (task) {
if (task.isReady()) {
task.doTask();
}
}
}
}
}
But it is a stupid use of CPU time. How to wait several objects?
IMO CountDownLatch would be a good way of going about it. Quoting from the 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() { ... }
}
Please use notifyaAll()
instead of notify()
because notify wakes up single thread where as notifyAll() wakes up all the waiting threads.
If you can modify the BackgroundTask
class, have it notify your runner when it is ready. Add a queue to your runner class, and each time a task is ready, it can add itself to the queue and notify it.
The runner class then waits on the queue when it is empty, and pulls items out of it to run when it is not.
You can utilize notify()
and wait()
on the Object. How you use it depends on the struture of your program.
精彩评论