线程池&CompletableFuture异步编排复习笔记

一、线程回顾

1.1 初始化线程的 4 种方式

1)、继承 Thread

java 复制代码
public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
        }
    }

2)、实现 Runnable 接口

java 复制代码
public static class Runable01 implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
        }
    }

3)、实现 Callable 接口 + FutureTask (可以拿到返回结果,可以处理异常)

java 复制代码
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;
        }
    }
public static void main(String[] args) {
		FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
}

4)、线程池

方式 1 和方式 2:主进程无法获取线程的运算结果。不适合当前场景

方式 3:主进程可以获取线程的运算结果,但是不利于控制服务器中的线程资源。可以导致服务器资源耗尽。

方式 4:通过如下两种方式初始化线程池

java 复制代码
Executors.newFiexedThreadPool(3);
//或者
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit unit, workQueue, threadFactory, handler);

通过线程池性能稳定 ,也可以获取执行结果 ,并捕获异常 。但是,在业务复杂情况下,一个异步调用可能会依赖于另一个异步调用的执行结果。

1.2 线程池的七大参数

java 复制代码
@param **corePoolSize** the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set
池中一直保持的线程的数量,即使线程空闲。除非设置了 allowCoreThreadTimeOut

@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. 
当线程数大于核心线程数的时候,线程在最大多长时间没有接到新任务就会终止释放,
最终线程池维持在 corePoolSize 大小

@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. 
阻塞队列,用来存储等待执行的任务,如果当前对线程的需求超过了 corePoolSize
大小,就会放在这里等待空闲线程执行。

@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
拒绝策略,如果线程满了,线程池就会使用拒绝策略。

运行流程 :

1、线程池创建,准备好 core 数量的核心线程,准备接受任务

2、新的任务进来,用 core 准备好的空闲线程执行。

(1) 、core 满了,就将再进来的任务放入阻塞队列中。空闲的 core 就会自己去阻塞队列获取任务执行

(2) 、阻塞队列满了,就直接开新线程执行,最大只能开到 max 指定的数量

(3) 、max 都执行好了。Max-core 数量空闲的线程会在 keepAliveTime 指定的时间后自动销毁。最终保持到 core 大小

(4) 、如果线程数开到了 max 的数量,还有新任务进来,就会使用 reject 指定的拒绝策略进行处理

3、所有的线程创建都是由指定的 factory 创建的。

面试问题 :

一个线程池 core 7; max 20 ,queue:50,100 并发进来怎么分配的:

先有 7 个能直接得到执行,接下来 50 个进入队列排队,在多开 13 个线程继续执行。现在 70 个被安排上了。剩下 30 个默认拒绝策略。

1.3 常见的 4 种线程池

  • newCachedThreadPool
    core=0,创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
  • newFixedThreadPool:
    core = max,创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
  • newScheduledThreadPool
    创建一个定长线程池,支持定时及周期性任务执行。
  • newSingleThreadExecutor
    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

1.4 开发中为什么使用线程池

  • 降低资源的消耗
    通过重复利用已经创建好的线程降低线程的创建和销毁带来的损耗。
  • 提高响应速度
    因为线程池中的线程数没有超过线程池的最大上限时,有的线程处于等待分配任务的状态,当任务来时无需创建新的线程就能执行
  • 提高线程的可管理性
    线程池会根据当前系统特点对池内的线程进行优化处理,减少创建和销毁线程带来的系统开销。无限的创建和销毁线程不仅消耗系统资源,还降低系统的稳定性,使用线程池进行统一分配

二、CompletableFuture 异步编排

业务场景 :

查询商品详情页的逻辑比较复杂,有些数据还需要远程调用,必然需要花费更多的时间。

假如商品详情页的每个查询,需要如下标注的时间才能完成,

那么,用户需要 5.5s 后才能看到商品详情页的内容。很显然是不能接受的。

如果有多个线程 同时完成这 6 步操作,也许只需要 1.5s 即可完成响应。

2.0 初步认识

在 Java 8 中, 新增加了一个包含 50 个方法左右的类: CompletableFuture ,提供了非常强大的Future 的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以

通过回调的方式处理计算结果,并且提供了转换和组合 CompletableFuture 的方法。CompletableFuture 类实现了 Future 接口,所以你还是可以像以前一样通过get方法阻塞或

者轮询的方式获得结果,但是这种方式不推荐使用。

CompletableFuture 和 FutureTask 同属于 Future 接口的实现类,都可以获取线程的执行结果。

注意(后续不再强调) :CompletableFuture中方法不以 Async 结尾,意味着 Action 使用相同的线程 执行,而 Async 可能会使用其他线程执行(如果是使用相同的线程池,也可能会被同一个线程选中执行)

2.1 创建异步对象

CompletableFuture 提供了四个静态方法来创建一个异步操作。

区别:
1、runXxxx 都是没有返回结果的,supplyXxx 都是可以获取返回结果的
2、可以传入自定义的线程池(推荐使用),否则就用默认的线程池;

2.2 计算完成时回调方法


whenComplete系列方法只能感知异常,不能修改CompletableFuture的返回值,若要返回异常信息,可以再链式调用exceptionally()方法,并指定一个出现异常以后默认的返回值。

whenComplete()需要传入参数 "消费者" BiConsumer<? super T, ? super Throwable> action,BiConsumer中accept(t,u)方法接收两个参数,第一个参数是future的返回结果,第二个参数是抛出的异常,没有返回值。

java 复制代码
public class ThreadTest {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    	System.out.println("main......start.....");
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
             System.out.println("当前线程:" + Thread.currentThread().getId());
             int i = 10 / 0;
             System.out.println("运行结果:" + i);
             return i;
         }, executor).whenComplete((res,exception) -> {
             //虽然能得到异常信息,但是没法修改返回数据
             System.out.println("异步任务成功完成了...结果是:" + res + "异常是:" + exception);
         }).exceptionally(throwable -> {
             //可以感知异常,同时返回默认值
             return 10;
         });
		System.out.println("main......end....." + future.get());
	}
}

执行结果:

java 复制代码
main......start.....
当前线程:20
异步任务成功完成了...结果是:null异常是:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
main......end.....10

2.3 handle 方法


和 whenComplete 一样,可对结果做最后的处理(可处理异常),可改变返回值。

handle()方法需要传入参数 BiFunction<? super T, Throwable, ? extends U> fn,BiFunction中的R apply(T t, U u)方法接收两个参数T t 和 U u ,并且有返回值R 。

java 复制代码
public class ThreadTest {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    	System.out.println("main......start.....");
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
             System.out.println("当前线程:" + Thread.currentThread().getId());
             int i = 10 / 2;
             System.out.println("运行结果:" + i);
             return i;
         }, executor).handle((result,thr) -> {
             if (result != null) {
                 return result * 2;
             }
             if (thr != null) {
                 System.out.println("异步任务成功完成了...结果是:" + result + "异常是:" + thr);
                 return 0;
             }
             return 0;
         });
		System.out.println("main......end....." + future.get());
	}
}

执行结果:

java 复制代码
main......start.....
当前线程:20
运行结果:5
main......end.....10

2.4 线程串行化方法


假设B线程需要A线程执行完成之后才能继续执行,则需要线程串行化。

  • thenRun系列方法,不需要依赖A返回的结果,没有返回值。
  • thenAccept系列方法,需要依赖A返回的结果,没有返回值。
  • thenApply系列方法,依赖A返回的结果,有返回值。

具体看三类方法的参数也能看出来:
thenRun 系列方法,只传入Runnable行为(不依赖结果),返回值类型是void(无返回值)。

java 复制代码
public CompletableFuture<Void> thenRun(Runnable action)

thenAccept 系列方法,传入Consumer<? super T> action,只做消费处理(依赖结果),返回值类型是void(无返回值)。

java 复制代码
public CompletableFuture<Void> thenAccept(Consumer<? super T> action)

thenApply 系列方法,传入Function<? super T,? extends U> fn,函数处理(依赖结果),返回值类型是U(有返回值)。

java 复制代码
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)

2.5 两任务组合 - 都要完成



两个任务必须都完成,触发该任务。

  • runAfterBoth:组合两个 future,不需要获取 future 的结果,只需两个 future 处理完任务后,处理该任务。
  • thenAcceptBoth:组合两个 future,获取两个 future 任务的返回结果,然后处理任务,没有返回值。
  • thenCombine:组合两个 future,获取两个 future 的返回结果,并返回当前任务的返回值。

2.6 两任务组合 - 一个完成



当两个任务中,任意一个 future 任务完成的时候,执行任务。

  • runAfterEither :两个任务有一个执行完成,不需要获取 future 的结果,处理任务,也没有返
    回值。
  • acceptEither:两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值。
  • applyToEither:两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值。

2.7 多任务组合

allOf:等待所有任务完成。

anyOf:只要有任何一个任务完成。

相关推荐
重生之小比特7 小时前
【C++进阶】异常
开发语言·c++
朝朝辞暮i7 小时前
C++ 第 15 课:指针 * 和地址 &
开发语言·c++
蜗牛互联网7 小时前
GPT-6.1 Sol迁移指南:从token单价转向每任务成本门禁
java·人工智能·后端·gpt
奶茶树7 小时前
【C++】14. C++11新特性【下】
开发语言·c++
web打印社区7 小时前
汽修 / 4S 店:维修工单、结算单网页怎么静默出纸
开发语言·前端·javascript·chrome·ecmascript
蜗牛互联网7 小时前
HSTU在Dynamo-Triton中的AOTI与KV缓存验收方法
java·人工智能·后端·缓存
Sirens.7 小时前
Java多线程实例:单例模式、阻塞队列、线程池与定时器
java·开发语言·单例模式
青山木7 小时前
秒杀系统设计(一):需求拆解与流量治理
java·数据库·redis·后端·架构
zhangrelay8 小时前
机器人或计算机智能与时间相关案例汇总(ROS2-ROS1)
linux·笔记·学习·ubuntu·机器人
卓怡学长8 小时前
w195基于ssm“Fitfrend”个性化健身
java·intellij-idea