假設我在一個程序中有多個Runnable實例,所有實例都由一個Executor實例分派。此外,假設我在某些時候需要等待這些可運行子集的一個子集才能繼續前進。我能做到這一點我可以以更好的方式加入主題嗎?
的一種方法如下:然後
public abstract class Joinable implements Runnable {
private final Semaphore finishedLock = new Semaphore(1);
@Override
public final void run() {
try {
finishedLock.acquireUninterruptibly();
doWork();
} finally {
finishedLock.release();
}
}
public abstract void doWork();
public void join() {
finishedLock.acquireUninterruptibly();
}
}
實現類可以簡單地重寫的doWork(),而不是運行(),以界定什麼應該執行期間進行。
連接過程會那麼只需像這樣:
void doStuff() {
Executor executor = Executors.newCachedThreadPool();
List<Joinable> joinables = new LinkedList<Joinable>();
// Fill joinables with implementors of Joinable...
List<Runnable> others = new LinkedList<Runnable>();
// Fill others with implementors of Runnable...
for(Joinable joinable : joinables)
executor.execute(joinable);
for(Runnable runnable : others)
executor.execute(runnable);
for(Joinable joinable : joinables)
joinable.join();
// Continue, no matter what the threads in others are up to.
}
這是解決這個問題(是連安全?)一個很好的方式,或者是有一個更好的?
我也喜歡其他的答案,但是隨着我的項目的整體設計進行得很順利,我就選擇了這個答案。 – csvan 2013-03-27 09:52:24