对于JDK8及以上版本通过CompletableFuture.anyOf实现多任务同时进行,只要有一个任务完成即结束应用场景,具体代码如下>>
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@import java.util.function.Supplier;@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 CompletableFutureAnyOfTest {@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.anyOf(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@main:main end******************@b@pool-1-thread-2:task2>>>>>>>>>>>@b@main:task2 get******************:task2@b@main:task2 end******************@b@main:task1 get******************:task1@b@main:task1 end******************