本文主要是介绍异步任务组合神器CompletableFuture,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用Demo
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;public class CompletableFutureDemo {private static AtomicInteger count = new AtomicInteger(2);public static void main(String[] args) throws InterruptedException, ExecutionException {// 准备10个线程ExecutorService executorService = Executors.newFixedThreadPool(2);long start = System.currentTimeMillis();// 模拟处理订单CompletableFuture<Void> dealOrder = CompletableFuture.runAsync(() -> {// 模拟任务耗时 0~4秒try {int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());} catch (InterruptedException e) {e.printStackTrace();}}, executorService);// 模拟处理库存CompletableFuture<Void> dealStock = CompletableFuture.runAsync(() -> {// 模拟任务耗时 0~4秒try {int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());} catch (InterruptedException e) {e.printStackTrace();}}, executorService);// 可变参数,可以传任意个CompletableFuture,阻塞等待所有任务完成CompletableFuture.allOf(dealOrder, dealStock).get();// 最终全部任务完成,总耗时取决于最耗时的任务时长System.out.println("all task is completed! cost: " + (System.currentTimeMillis() - start) + "ms");}
}
能做什么
比如你需要做这种,任务B和C都执行完后,再执行任务A的情况,就可以使用
这篇关于异步任务组合神器CompletableFuture的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!