一、线程回顾
初始化线程的 4 种方式
-
继承 Thread
-
public class test { public static void main(String[] args) { System.out.println("main方法。。。。。。开始"); Thread01 thread01 = new Thread01(); thread01.start();//启动线程 System.out.println("main方法。。。。。。结束"); } public static class Thread01 extends Thread { @Override public void run() { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); } } }
结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:11
运行结果:5
-
-
实现 Runnable 接口
-
public class test { public static void main(String[] args) { System.out.println("main方法。。。。。。开始"); Thread thread = new Thread(new Runable01()); thread.start();//启动线程 System.out.println("main方法。。。。。。结束"); } public static class Runable01 implements Runnable { @Override public void run() { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); } } }
结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:12
运行结果:5
-
-
实现 Callable 接口 + FutureTask (可以拿到返回结果, 可以处理异常)
-
public class test { public static void main(String[] args) { System.out.println("main方法。。。。。。开始"); FutureTask<Integer> integerFutureTask = new FutureTask<>(new Callable01()); new Thread(integerFutureTask).start(); System.out.println("main方法。。。。。。结束"); } public static class Callable01 implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); return i; } } }
结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:13
运行结果:5
-
public class test { public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main方法。。。。。。开始"); //也可以在这传入要接受结果的参数 FutureTask<Integer> integerFutureTask = new FutureTask<>(new Callable01()); new Thread(integerFutureTask).start(); //阻塞等待整个线程执行完成获取返回结果 Integer integer = integerFutureTask.get(); System.out.println("main方法。。。。。。结束"+integer); } public static class Callable01 implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); return i; } } }
结果:
main方法。。。。。。开始
当前线程:14
运行结果:5
main方法。。。。。。结束5
-
-
线程池(ExecutorService)
如:
public class test { //当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行 public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main方法。。。。。。开始"); executorService.execute(new Runable01()); System.out.println("main方法。。。。。。结束"); } public static class Runable01 implements Runnable { @Override public void run() { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); } } }
结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:14
运行结果:5
方式 1 和方式 2:主进程无法获取线程的运算结果。 不适合当前场景
方式 3:主进程可以获取线程的运算结果, 但是不利于控制服务器中的线程资源。 可以导致服务器资源耗尽。
我们以后再业务代码里面,以上三种启动线程的方式我们都不用,将所有的多线程异步任务都交给线程池执行
方式 4:可以控制资源,性能稳定,通过如下两种方式初始化线程池
Executors.newFiexedThreadPool(3);
//或者
new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,TimeUnit unit,workQueue,threadFactory,handler);
通过线程池性能稳定, 也可以获取执行结果, 并捕获异常。 但是, 在业务复杂情况下, 一个异步调用可能会依赖于另一个异步调用的执行结果。
线程池的七大参数
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
- corePoolSize: 核心线线程数,池中一直保持的线程的数量,即使线程空闲。除非设置了 allowCoreThreadTimeOut过期
- maximumPoolSize: 池中允许的最大的线程,控制资源
- keepAliveTime: 当线程数大于核心线程数的时候,超出核心线程数的线程在最大多长时间没有接到新任务就会终止释放(释放空闲的线程),最终线程池维持在 corePoolSize 大小
- unit: 时间单位
- workQueue: 阻塞队列,用来存储等待执行的任务,如果当前对线程的需求超过了 corePoolSize大小,就会放在这里等待空闲线程执行
- threadFactory:创建线程的工厂,比如指定线程名等
- handler:拒绝策略,如果线程满了,线程池就会使用拒绝策略。
运行流程:
- 线程池创建, 准备好 core 数量的核心线程, 准备接受任务
- 新的任务进来, 用 core 准备好的空闲线程执行
- core 满了, 就将再进来的任务放入阻塞队列中。 空闲的 core 就会自己去阻塞队列获取任务执行
- 阻塞队列满了, 就直接开新线程执行, 最大只能开到 max 指定的数量
- max 都执行好了。 Max-core 数量空闲的线程会在 keepAliveTime 指定的时间后自动销毁。 最终保持到 core 大小
- 如果线程数开到了 max 的数量, 还有新任务进来, 就会使用 reject 指定的拒绝策略进行处理
- 所有的线程创建都是由指定的 factory 创建的。
面试:
一个线程池 core 7; max 20 , queue: 50, 100 并发进来怎么分配的?
先有 7 个能直接得到执行, 接下来 50 个进入队列排队, 在多开 13 个继续执行。 现在 70 个被安排上了。 剩下 30 个默认拒绝策略(不想抛弃可以使用CallerRunsPolicy拒绝策略)。
常见的 4 种线程池
-
newCachedThreadPool
- 创建一个可缓存线程池, 如果线程池长度超过处理需要, 可灵活回收空闲线程, 若无可回收, 则新建线程。(core核心是0,所有都可以回收)
-
newFixedThreadPool
- 创建一个定长线程池, 可控制线程最大并发数, 超出的线程会在队列中等待。(固定大小,core=max,都不可回收)
-
newScheduledThreadPool
- 创建一个定长线程池, 支持定时及周期性任务执行。(定时任务)
-
newSingleThreadExecutor
- 创建一个单线程化的线程池, 它只会用唯一的工作线程来执行任务, 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
开发中为什么使用线程池
- 降低资源的消耗
- 通过重复利用已经创建好的线程降低线程的创建和销毁带来的损耗
- 提高响应速度
- 因为线程池中的线程数没有超过线程池的最大上限时, 有的线程处于等待分配任务的状态, 当任务来时无需创建新的线程就能执行
- 提高线程的可管理性
- 线程池会根据当前系统特点对池内的线程进行优化处理, 减少创建和销毁线程带来的系统开销。 无限的创建和销毁线程不仅消耗系统资源, 还降低系统的稳定性, 使用线程池进行统一分配
二、CompletableFuture 异步编排
业务场景:
查询商品详情页的逻辑比较复杂, 有些数据还需要远程调用, 必然需要花费更多的时间
// 获取sku的基本信息 0.5s
// 获取sku的图片信息 0.5s
// 获取sku的促销信息 1s
// 获取spu的所有销售属性 1s
// 获取规格参数组及组下的规格参数 1.5s、
// spu详情 1s
假如商品详情页的每个查询, 需要如下标注的时间才能完成
那么, 用户需要 5.5s 后才能看到商品详情页的内容。 很显然是不能接受的。
如果有多个线程同时完成这 6 步操作, 也许只需要 1.5s 即可完成响应。
Future 是 Java 5 添加的类, 用来描述一个异步计算的结果。 你可以使用isDone
方法检查计算是否完成, 或者使用get
阻塞住调用线程, 直到计算完成返回结果, 你也可以使用cancel
方法停止任务的执行。
虽然Future
以及相关使用方法提供了异步执行任务的能力, 但是对于结果的获取却是很不方便, 只能通过阻塞或者轮询的方式得到任务的结果。 阻塞的方式显然和我们的异步编程的初衷相违背, 轮询的方式又会耗费无谓的 CPU 资源, 而且也不能及时地得到计算结果, 为什么不能用观察者设计模式当计算结果完成及时通知监听者呢?
很多语言, 比如 Node.js, 采用回调的方式实现异步编程。 Java 的一些框架, 比如 Netty, 自己扩展了 Java 的 Future
接口, 提供了addListener
等多个扩展方法; Google guava 也提供了通用的扩展 Future; Scala 也提供了简单易用且功能强大的 Future/Promise 异步编程模式。
作为正统的 Java 类库, 是不是应该做点什么, 加强一下自身库的功能呢?
在 Java 8 中, 新增加了一个包含 50 个方法左右的类: CompletableFuture, 提供了非常强大的Future 的扩展功能, 可以帮助我们简化异步编程的复杂性, 提供了函数式编程的能力, 可以通过回调的方式处理计算结果, 并且提供了转换和组合 CompletableFuture 的方法。
CompletableFuture 类实现了 Future 接口, 所以你还是可以像以前一样通过get
方法阻塞或者轮询的方式获得结果, 但是这种方式不推荐使用。
CompletableFuture 和 FutureTask 同属于 Future 接口的实现类, 都可以获取线程的执行结果。
创建异步对象
CompletableFuture 提供了四个静态方法来创建一个异步操作。
public static CompletableFuture<Void> runAsync(Runnable runnable) {
return asyncRunStage(ASYNC_POOL, runnable);
}
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) {
return asyncRunStage(screenExecutor(executor), runnable);
}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(ASYNC_POOL, supplier);
}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
-
runXxxx 都是没有返回结果的, supplyXxx 都是可以获取返回结果的
-
public class test { //当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行 public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main方法。。。。。。开始"); CompletableFuture<Void> future = CompletableFuture.runAsync(new Runable01(), executorService); System.out.println("main方法。。。。。。结束"); } public static class Runable01 implements Runnable { @Override public void run() { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); } } }
结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:14
运行结果:5 -
public class test { //当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行 public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main方法。。。。。。开始"); CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("运行结果:" + i); return i; }, executorService); Integer o = future.get(); System.out.println("main方法。。。。。。结束"+o); } }
结果:
main方法。。。。。。开始
当前线程:14
运行结果:5
main方法。。。。。。结束5
-
-
可以传入自定义的线程池, 否则就用默认的线程池
计算完成时回调方法
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(null, action);
}
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(defaultExecutor(), action);
}
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor) {
return uniWhenCompleteStage(screenExecutor(executor), action);
}
public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn) {
return uniExceptionallyStage(fn);
}
whenComplete 可以接受正常返回和感知异常, exceptionally 处理异常结果。
whenComplete 和 whenCompleteAsync 的区别:
-
whenComplete: 是执行当前任务的线程执行继续执行whenComplete 的任务。
public class test { //当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行 public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main方法。。。。。。开始"); CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { System.out.println("当前线程:" + Thread.currentThread().getId()); //方式一:int i = 10 / 2; 方式二:int i = 10 / 0; System.out.println("运行结果:" + i); return i; }, executorService).whenComplete((result,exception)->{ System.out.println("异常任务成功完成了。。。结果是:" + result + "异常是:" + exception); }); // Integer o = future.get(); System.out.println("main方法。。。。。。结束"); } }
方式一结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:14
运行结果:5
异常任务成功完成了。。。结果是:5异常是:null方式二结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:14
异常任务成功完成了。。。结果是:null异常是:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero -
whenCompleteAsync: 是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。
-
exceptionally
-
public class test { //当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行 public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main方法。。。。。。开始"); CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { System.out.println("当前线程:" + Thread.currentThread().getId()); int i = 10 / 0; System.out.println("运行结果:" + i); return i; }, executorService).whenComplete((result,exception)->{ //能得到异常信息但是没法修改返回数据 System.out.println("异常任务成功完成了。。。结果是:" + result + "异常是:" + exception); }).exceptionally(t -> { //异常后返回默认值 return 10; }); Integer o = future.get(); System.out.println("main方法。。。。。。结束" + o); } }
结果:
main方法。。。。。。开始
当前线程:14
异常任务成功完成了。。。结果是:null异常是:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
main方法。。。。。。结束10
-
方法不以 Async 结尾, 意味着 Action 使用相同的线程执行, 而 Async 可能会使用其他线程执行(如果是使用相同的线程池, 也可能会被同一个线程选中执行)
handle 方法
public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
return uniHandleStage(screenExecutor(executor), fn);
}
和 complete 一样, 可对结果做最后的处理(可处理异常) , 可改变返回值。
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 0;
System.out.println("运行结果:" + i);
return i;
}, executorService).handle((result,exception)->{
if (result != null) {
return result * 2;
}
if (exception != null) {
return -1;
}
return 0;
});
Integer o = future.get();
System.out.println("main方法。。。。。。结束" + o);
}
}
结果:
main方法。。。。。。开始
当前线程:14
main方法。。。。。。结束-1
线程串行化方法
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn) {
return uniApplyStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor) {
return uniApplyStage(screenExecutor(executor), fn);
}
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
return uniAcceptStage(null, action);
}
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
return uniAcceptStage(defaultExecutor(), action);
}
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
Executor executor) {
return uniAcceptStage(screenExecutor(executor), action);
}
public CompletableFuture<Void> thenRun(Runnable action) {
return uniRunStage(null, action);
}
public CompletableFuture<Void> thenRunAsync(Runnable action) {
return uniRunStage(defaultExecutor(), action);
}
public CompletableFuture<Void> thenRunAsync(Runnable action,Executor executor) {
return uniRunStage(screenExecutor(executor), action);
}
thenApply 方法: 当一个线程依赖另一个线程时, 获取上一个任务返回的结果, 并返回当前任务的返回值。
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("运行结果:" + i);
return i;
}, executorService).thenApplyAsync((result) -> {
System.out.println("任务二启动了。。。" + result);
return "Hello" + result;
}, executorService);
System.out.println("main方法。。。。。。结束" + stringCompletableFuture.get());
}
}
结果:
main方法。。。。。。开始
当前线程:14
运行结果:2
任务二启动了。。。2
main方法。。。。。。结束Hello2
thenAccept 方法: 消费处理结果。 接收任务的处理结果, 并消费处理, 无返回结果。
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("运行结果:" + i);
return i;
}, executorService).thenAcceptAsync((result) -> {
System.out.println("任务二启动了。。。" + result);
}, executorService);
System.out.println("main方法。。。。。。结束");
}
}
结果:
main方法。。。。。。开始
main方法。。。。。。结束
当前线程:14
运行结果:2
任务二启动了。。。2
thenRun 方法: 只要上面的任务执行完成, 就开始执行 thenRun, 只是处理完任务后, 执行thenRun 的后续操作
带有 Async 默认是异步执行的。 同之前。
以上都要前置任务成功完成。
Function<? super T,? extends U>
T: 上一个任务返回结果的类型
U: 当前任务的返回值类型
如:
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("运行结果:" + i);
return i;
}, executorService).thenRunAsync(() -> {
System.out.println("任务二启动了。。。");
}, executorService);
System.out.println("main方法。。。。。。结束");
}
}
两任务组合 - 都要完成
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn) {
return biApplyStage(null, other, fn);
}
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn) {
return biApplyStage(defaultExecutor(), other, fn);
}
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
return biApplyStage(screenExecutor(executor), other, fn);
}
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action) {
return biAcceptStage(null, other, action);
}
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action) {
return biAcceptStage(defaultExecutor(), other, action);
}
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor) {
return biAcceptStage(screenExecutor(executor), other, action);
}
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,Runnable action) {
return biRunStage(null, other, action);
}
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action) {
return biRunStage(defaultExecutor(), other, action);
}
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor) {
return biRunStage(screenExecutor(executor), other, action);
}
两个任务必须都完成, 触发该任务。
thenCombine: 组合两个 future, 获取两个 future 的返回结果, 并返回当前任务的返回值
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("任务1运行结果:" + i);
return i;
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2运行结果:");
return "Hello";
}, executorService);
CompletableFuture<String> stringCompletableFuture = future1.thenCombineAsync(future2, (f1, f2) -> {
return "f1=" + f1 + ",f2=" + f2;
}, executorService);
System.out.println("main方法。。。。。。结束" + stringCompletableFuture.get());
}
}
结果:
main方法。。。。。。开始
任务1线程:14
任务2线程:15
任务2运行结果:
任务1运行结果:2
main方法。。。。。。结束f1=2,f2=Hello
thenAcceptBoth: 组合两个 future, 获取两个 future 任务的返回结果, 然后处理任务, 没有返回值。
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("任务1运行结果:" + i);
return i;
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2运行结果:");
return "Hello";
}, executorService);
future1.thenAcceptBothAsync(future2,(f1,f2)->{
System.out.println("任务3开始。。。之前的结果,f1=" + f1 + "--->f2=" + f2);
}, executorService);
System.out.println("main方法。。。。。。结束");
}
}
结果:
main方法。。。。。。开始
main方法。。。。。。结束
任务1线程:14
任务2线程:15
任务2运行结果:
任务1运行结果:2
任务3开始。。。之前的结果,f1=2—>f2=Hello
runAfterBoth: 组合两个 future, 不需要获取 future 的结果, 只需两个 future 处理完任务后,处理该任务
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("任务1运行结果:" + i);
return i;
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2运行结果:");
return "Hello";
}, executorService);
future1.runAfterBoth(future2, () -> {
System.out.println("任务3开始");
});
System.out.println("main方法。。。。。。结束");
}
}
结果:
main方法。。。。。。开始
main方法。。。。。。结束
任务1线程:14
任务2线程:15
任务2运行结果:
任务1运行结果:2
任务3开始
两任务组合 - 一个完成
public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn) {
return orApplyStage(null, other, fn);
}
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn) {
return orApplyStage(defaultExecutor(), other, fn);
}
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn,Executor executor) {
return orApplyStage(screenExecutor(executor), other, fn);
}
public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) {
return orAcceptStage(null, other, action);
}
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action) {
return orAcceptStage(defaultExecutor(), other, action);
}
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action,Executor executor) {
return orAcceptStage(screenExecutor(executor), other, action);
}
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,Runnable action) {
return orRunStage(null, other, action);
}
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action) {
return orRunStage(defaultExecutor(), other, action);
}
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor) {
return orRunStage(screenExecutor(executor), other, action);
}
当两个任务中, 任意一个 future 任务完成的时候, 执行任务。
applyToEither: 两个任务有一个执行完成, 获取它的返回值, 处理任务并有新的返回值。
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("任务1运行结果:" + i);
return i;
}, executorService);
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2运行结果:");
try {
TimeUnit.MILLISECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
}, executorService);
CompletableFuture<String> stringCompletableFuture = future1.applyToEitherAsync(future2, (result) -> {
System.out.println("任务3开始。。。之前的结果" + result);
return result.toString() + "哈哈";
}, executorService);
System.out.println("main方法。。。。。。结束"+stringCompletableFuture.get());
}
}
结果:
main方法。。。。。。开始
任务1线程:16
任务2线程:17
任务2运行结果:
任务1运行结果:2
任务3开始。。。之前的结果Hello
main方法。。。。。。结束Hello哈哈
acceptEither: 两个任务有一个执行完成, 获取它的返回值, 处理任务, 没有新的返回值。
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("任务1运行结果:" + i);
return i;
}, executorService);
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2运行结果:");
try {
TimeUnit.MILLISECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
}, executorService);
future1.acceptEitherAsync(future2, (result) -> {
System.out.println("任务3开始。。。之前的结果"+result);
}, executorService);
System.out.println("main方法。。。。。。结束");
}
}
结果:
main方法。。。。。。开始
main方法。。。。。。结束
任务1线程:14
任务2线程:15
任务2运行结果:
任务1运行结果:2
任务3开始。。。之前的结果Hello
runAfterEither: 两个任务有一个执行完成, 不需要获取 future 的结果, 处理任务, 也没有返回值
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 10 / 4;
System.out.println("任务1运行结果:" + i);
return i;
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2运行结果:");
try {
TimeUnit.MILLISECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
}, executorService);
future1.runAfterEitherAsync(future2, () -> {
System.out.println("任务3开始。。。之前的结果");
}, executorService);
System.out.println("main方法。。。。。。结束");
}
}
结果:
main方法。。。。。。开始
main方法。。。。。。结束
任务1线程:14
任务2线程:15
任务2运行结果:
任务3开始。。。之前的结果
任务1运行结果:2
多任务组合
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
return andTree(cfs, 0, cfs.length - 1);
}
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
int n; Object r;
if ((n = cfs.length) <= 1)
return (n == 0)
? new CompletableFuture<Object>()
: uniCopyStage(cfs[0]);
for (CompletableFuture<?> cf : cfs)
if ((r = cf.result) != null)
return new CompletableFuture<Object>(encodeRelay(r));
cfs = cfs.clone();
CompletableFuture<Object> d = new CompletableFuture<>();
for (CompletableFuture<?> cf : cfs)
cf.unipush(new AnyOf(d, cf, cfs));
// If d was completed while we were adding completions, we should
// clean the stack of any sources that may have had completions
// pushed on their stack after d was completed.
if (d.result != null)
for (int i = 0, len = cfs.length; i < len; i++)
if (cfs[i].result != null)
for (i++; i < len; i++)
if (cfs[i].result == null)
cfs[i].cleanStack();
return d;
}
allOf: 等待所有任务完成
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询图片信息");
return "img";
}, executorService);
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询规格信息");
return "256G";
}, executorService);
CompletableFuture<Object> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询介绍");
return "华为";
}, executorService);
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(future1, future2, future3);
// voidCompletableFuture.join();
voidCompletableFuture.get();
System.out.println("main方法。。。。。。结束");
}
}
结果:
main方法。。。。。。开始
查询图片信息
查询规格信息
查询介绍
main方法。。。。。。结束
anyOf: 只要有一个任务完成
public class test {
//当前系统中池只有一两个,每隔异步任务,提交给线程池让他自己去执行就行
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main方法。。。。。。开始");
CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询图片信息");
return "img";
}, executorService);
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询规格信息");
return "256G";
}, executorService);
CompletableFuture<Object> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询介绍");
return "华为";
}, executorService);
CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future1, future2, future3);
// voidCompletableFuture.join();
objectCompletableFuture.get();
System.out.println("main方法。。。。。。结束"+objectCompletableFuture.get());
}
结果:
main方法。。。。。。开始
查询图片信息
查询规格信息
查询介绍
main方法。。。。。。结束img