프로그램 내에 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