多线程CountDownLatch的应用

1.创建线程池

ExecutorService executorService;
executorService = Executors.newFixedThreadPool(4);

2.声明CountDownLatch,用户计算线程完成的数量,vehicleList.size()是要处理的数据总条数。

CountDownLatch latch = new CountDownLatch(vehicleList.size());

3.将对象latch传入线程类

Callable c = new GetTrackCallableService(callableEntity, hyHttpUtil,latch);

4.在call方法中执行latch.countDown();每次线程跑完就会加一

@Override
public Map<String, Object> call() {
Map<String,Object> rMap = new HashMap<>();
try {
//处理业务逻辑
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
return rMap;
}

5.在循环处理之后写latch.await();表示在latch计数完成后,才向下执行,保证了线程全部执行完毕。

latch.await();

6.另:call方法支持返回值,可用Future f = 接收,f.get()执行并接收返回值。也可以通过向call中传入变量接收。

猜你喜欢

转载自www.cnblogs.com/Steward-Sun/p/9728059.html