- 创建
//创建阻塞队列
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
//创建线程池
ThreadPoolExecutor executorService = new ThreadPoolExecutor(8, 8, 5, TimeUnit.MINUTES, queue, (runnbale) -> {
Thread t = new Thread(runnbale);
t.setName("自定义线程");
t.setDaemon(true);
return t;
});
//预启动所有核心线程
executorService.prestartAllCoreThreads();
- 使用
executorService.execute(() -> {
try {
log.info("OrderDataBizServiceImpl.procurementOrderHandler 开始");
procurementOrderHandler(applyData);
log.info("OrderDataBizServiceImpl.procurementOrderHandler 完成");
} catch (Exception e) {
log.error("OrderDataBizServiceImpl.procurementOrderHandler 异常", e);
} finally {
countDownLatch.countDown();
}
});
第二种方式:
//创建一个线程池
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("tenantRuleWholeSearchPool").build();
ExecutorService executorService = new ThreadPoolExecutor(2, 2,10, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(2), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
//将任务添加到线程池
List<Runnable> tasks = Arrays.asList(
() -> amspmStrategSearch(amspmStrategyList, identityData, param, data, type),
() -> abilityListSearch(abilityList, identityData, param, data, type));
//逐个提交任务
tasks.forEach(executorService::submit);
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);