JB Nizet 给出了一个很好的答案。我拿了他的,稍微打磨了一下。结果是一个名为 AbortableCountDownLatch 的 CountDownLatch 的子类,它向该类添加了一个“abort()”方法,该方法将导致所有等待锁存器的线程接收 AbortException(InterruptedException 的子类)。
此外,与 JB 的类不同,AbortableCountDownLatch 将在中止时立即中止所有阻塞线程,而不是等待倒计时达到零(对于使用计数>1 的情况)。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class AbortableCountDownLatch extends CountDownLatch {
protected boolean aborted = false;
public AbortableCountDownLatch(int count) {
super(count);
}
/**
* Unblocks all threads waiting on this latch and cause them to receive an
* AbortedException. If the latch has already counted all the way down,
* this method does nothing.
*/
public void abort() {
if( getCount()==0 )
return;
this.aborted = true;
while(getCount()>0)
countDown();
}
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
final boolean rtrn = super.await(timeout,unit);
if (aborted)
throw new AbortedException();
return rtrn;
}
@Override
public void await() throws InterruptedException {
super.await();
if (aborted)
throw new AbortedException();
}
public static class AbortedException extends InterruptedException {
public AbortedException() {
}
public AbortedException(String detailMessage) {
super(detailMessage);
}
}
}