对于JDK8及以上版本通过CompletableFuture.anyOf及task1Future.thenApply实现多任务同时进行,虽然也是必须3个任务完成即结束,但是需先完成任务1才能做任务3的(任务2和任务1&3并行进行)顺序进行,具体代码如下>>
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 CompletableFutureForkAllOfTest {@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(2000);@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@ //task3必须等task1完成才能做@b@ CompletableFuture<String> task3Future = task1Future.thenApply(i -> {@b@ try{@b@ Thread.sleep(1000);@b@ System.out.println(Thread.currentThread().getName()+":task3>>>>>>>>>>>");@b@ }catch (Exception e){}@b@ return "task3";@b@ });@b@@b@ //等task2 & task3完成总任务才能结束@b@ CompletableFuture.allOf(task3Future,task2Future).join();@b@ //task1和task2只要有个完成即打印@b@ System.out.println(Thread.currentThread().getName()+":main end******************");@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@ System.out.println(Thread.currentThread().getName()+":task3 get******************:"+task3Future.get());@b@ System.out.println(Thread.currentThread().getName()+":task3 end******************");@b@@b@ }@b@@b@@b@@b@}
控制台打印结果
main:main start******************@b@pool-1-thread-2:task2>>>>>>>>>>>@b@pool-1-thread-1:task1>>>>>>>>>>>@b@pool-1-thread-1:task3>>>>>>>>>>>@b@main:main end******************@b@main:task2 get******************:task2@b@main:task2 end******************@b@main:task1 get******************:task1@b@main:task1 end******************@b@main:task3 get******************:task3@b@main:task3 end******************