Follow wx:CodingTechWork
need
A list operation needs to process each element asynchronously, and finally needs to return the operation results of each element of the list uniformly, without paying attention to the order of execution in the list. This thread pool does not guarantee the sequential execution of tasks, that is, WorkStealing preemptive work.
development template
Thread pool configuration
@Configuration
public class ThreadPoolConfig {
@Bean
public ExecutorService getThreadPool(){
//工作抢占式线程池
return Executors.newWorkStealingPool(20);
}
}
multi-thread call
/**
* 线程service
*/
@Autowired
private ExecutorService executorService;
/**
* 异步处理列表
*/
private Boolean asynDo(List<String> idList) {
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
//CompletableFuture 循环处理
idList.forEach(id -> {
CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() ->
this.setId(id), executorService);
//添加到异步汇总结果中
futures.add(future);
});
//校验总的异步结果
if (null != futures && !futures.isEmpty()) {
//等待所有线程执行完毕
futures.forEach(CompletableFuture::join);
//处理转发结果
for (CompletableFuture<Boolean> completableFuture : futures) {
try {
Boolean result = completableFuture.get();
if (null == result) {
log.error("asynDo失败,错误信息:结果为空!");
return false;
}
if (!result) {
//一个失败,则都失败
return false;
} else {
//一个成功,则继续
log.info("id={}成功", id);
}
} catch (InterruptedException e) {
log.error("asynDo失败,错误信息:{}", e.getMessage());
Thread.currentThread().interrupt();
return false;
} catch (ExecutionException e) {
log.error("asynDo失败,错误信息:{}", e.getMessage());
return false;
}
}
}
return true;
}
/**
* 单个处理
*/
private Boolean setId(String id) {
//TODO
... ...
}