1.线程池的创建:
在定义完线程池后,进行业务代码的处理:
public class ThreadPoolUtil {
/**
* 线程工厂定义
*/
private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build();
/**
* 线程池定义
*/
public static ThreadPoolExecutor executor =
new ThreadPoolExecutor(
5,
6,
10,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10000),
threadFactory);
/**
* 异步执行
*
* @param runnable
*/
public static void execute(Runnable runnable) {
executor.execute(runnable);
}
}
2.业务代码的处理 :
List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
completableFutures.add(CompletableFuture.runAsync(() ->{
//填充业务代码
}, ThreadPoolUtil.executor));
completableFutures.add(CompletableFuture.runAsync(() ->{
//填充业务代码
}, ThreadPoolUtil.executor));
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();