对于JDK8及以上版本通过CompletableFuture.allOf实现多任务并发进行,必须等到所有子任务完成后才能继续,代码如下:
package com.xwood.java8.threads;@b@@b@import java.util.concurrent.CompletableFuture;@b@import java.util.concurrent.ExecutorService;@b@import java.util.concurrent.Executors;@b@@b@/**@b@ * @author jun.ni@b@ * @version 1.0.0@b@ * @ClassName CompletableFutureAnyOfTest.java@b@ * @Description TODO@b@ * @createTime 2024/9/10 15:13@b@ */@b@public class CompletableFutureAllOfTest {@b@@b@ public static void main(String[] args) throws Exception {@b@@b@ System.out.println(Thread.currentThread().getName()+":main start******************");@b@@b@ ExecutorService executorService = Executors.newFixedThreadPool(10);@b@@b@ CompletableFuture<String> task1Future = CompletableFuture.supplyAsync( () -> {@b@ try{@b@ Thread.sleep(1000);@b@ System.out.println(Thread.currentThread().getName()+":task1>>>>>>>>>>>");@b@ }catch (Exception e){}@b@ return "task1";@b@ }, executorService);@b@@b@ CompletableFuture<String> task2Future = CompletableFuture.supplyAsync( () -> {@b@ try{@b@ Thread.sleep(2000);@b@ System.out.println(Thread.currentThread().getName()+":task2>>>>>>>>>>>");@b@ }catch (Exception e){}@b@ return "task2";@b@ }, executorService);@b@ //等所有任务完成总任务才能结束@b@ CompletableFuture.allOf(task1Future,task2Future).join();@b@ //task1和task2只要有个完成即打印@b@ System.out.println(Thread.currentThread().getName()+":main end******************");@b@@b@@b@ //等task2完成后,才能打印@b@ System.out.println(Thread.currentThread().getName()+":task2 get******************:"+task2Future.get());@b@ System.out.println(Thread.currentThread().getName()+":task2 end******************");@b@@b@ System.out.println(Thread.currentThread().getName()+":task1 get******************:"+task1Future.get());@b@ System.out.println(Thread.currentThread().getName()+":task1 end******************");@b@@b@ }@b@@b@@b@@b@}
控制台打印结果
main:main start******************@b@pool-1-thread-1:task1>>>>>>>>>>>@b@pool-1-thread-2:task2>>>>>>>>>>>@b@main:main end******************@b@main:task2 get******************:task2@b@main:task2 end******************@b@main:task1 get******************:task1@b@main:task1 end******************