在实际的开发中我们可能会遇到这样的问题:
需要并发的查询返回数据整合在一起,还需要设定超时,以免有一些东西查的实在太久,无法按时返回数据.我的思路是使用CountDownLatch实现.
public abstract class AbstractCallBackThread<T> implements Runnable{
private Consumer<T> callBack;
private CountDownLatch countDownLatch;
public AbstractCallBackThread(Consumer<T> callback, CountDownLatch countDownLatch){
this.callBack=callback;
this.countDownLatch=countDownLatch;
}
public abstract T handle();
@Override
public void run() {
T obj = handle();
callBack.accept(obj);
countDownLatch.countDown();
}
}
编写一个实现了Runable的抽象类,传入一个成功后的处理函数和一个Latch,成功后对Latch-1.
public static void main(String[] args) throws InterruptedException {
List<Object> result = new ArrayList<>();
CountDownLatch countDownLatch = new CountDownLatch(2);
AbstractCallBackThread<List<Object>> abstractCallBackThread = new AbstractCallBackThread<List<Object>>(result::addAll, countDownLatch) {
@Override
public List<Object> handle() {
return Collections.singletonList(10);
}
};
//放入线程池
Thread thread = new Thread(abstractCallBackThread);
thread.start();
//超时处理
countDownLatch.await(100, TimeUnit.MILLISECONDS);
System.out.println(result);
}