代码很简单,简单来说也就是。先创建一个线程池类,然后再写一个并发任务执行就可以了。因为此并发任务是利用
qvVerifyAsyncPool线程池处理的。
核心为,
- //定义线程返回结果
- List
> futures = new ArrayList>();
然后执行多个并发,同时将任务返回结果添加到此结果集合中
- CompletableFuture
future = CompletableFuture.supplyAsync(() -> { - //任务
-
- return 1;
- },qvVerifyAsyncPool);
添加并发任务结果
futures.add(future);
堵塞当所有的任务完成时返回结果
- //阻塞等待结果返回
- CompletableFuture
allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); - List
result = allFutures.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList())).join();
完整代码如下:
该线程池类代码如下:
- @Configuration
- @EnableAsync
- public class AsyncConfiguration {
-
-
- /**
- * 报告线程池--整个报告
- * @return ThreadPoolTaskExecutor
- */
- @Bean(name = "qvVerifyAsyncPool")
- public ThreadPoolExecutor QvVerifyAsyncPool(){
- return new ThreadPoolExecutor(
- //核心线程数
- qvCorePoolSize,
- //最大线程数
- qvMaxPoolSize,
- qvKeepAliveSeconds,
- TimeUnit.SECONDS,
- //队列大小
- new LinkedBlockingDeque
(qvQueueCapacity), - //定义线程名称
- new ThreadFactory() {
- private final AtomicInteger mThreadNum = new AtomicInteger(1);
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "qvVerifyAsyncPool-" + mThreadNum.getAndIncrement());
- }
- },
- //拒绝策略
- new ThreadPoolExecutor.AbortPolicy()
- );
- }
- }
- /**
- * 简单Java并行代码
- * @param
- */
- public List
simpleParallel(){ -
- List
> futures = new ArrayList<>(); - for (int i = 0; i <10 ; i++) {
- CompletableFuture
future = CompletableFuture.supplyAsync(() -> { - System.out.println("有返回值的异步任务"+Thread.currentThread().getName());
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- return 1;
- },qvVerifyAsyncPool);
-
- futures.add(future);
- }
-
- // 使用allOf方法来表示所有的并行任务
- CompletableFuture
allFutures = CompletableFuture.allOf( - futures.toArray(new CompletableFuture[futures.size()]));
-
-
- // 下面的方法可以帮助我们获得所有子任务的处理结果
- CompletableFuture
> finalResults = allFutures.thenApply(v ->
- futures.stream().map(CompletableFuture::join).collect(Collectors.toList())
- );
- List
resultList = finalResults.join(); -
- System.out.println(resultList);
-
- return resultList;
- }