异步&线程池
一、线程回顾
1、初始化线程的 4 种方式
- 继承 Thread
- 实现 Runnable 接口
- 实现 Callable 接口 + FutureTask (可以拿到返回结果,可以处理异常)
- 线程池
public class ThreadTest { public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static void main(String[] args) { /** * 1、继承Thread * Thread01 thread01 = new Thread01(); * thread01.start();//启动线程 * 2、实现Runnable * Runable01 runable01 = new Runable01(); * new Thread(runable01).start(); * 3、实现Callable接口 + FutureTask(可以拿到返回结果,可以处理异常) * FutureTask<Integer> futureTask = new FutureTask<>(new Callable01()); * new Thread(futureTask).start(); * Integer integer = futureTask.get(); * 4、线程池 * 任务直接提交至线程池。 * 区别: * 1、2不能得到返回值。3可以得到返回值 * 1、2、3不能控制资源 * 4、可以控制资源,性能稳定。 */ //123启动线程方式都不用,原因是启动线程不可控制,当线程过多时会导致资源浪费,系统崩溃的风险 //当前系统中保证线程池只有一两个,每个异步任务,提交给线程池去自己执行 executorService.execute(new Runable01()); } //继承Thread public static class Thread01 extends Thread{ @Override public void run(){ System.out.println("当前线程:"+Thread.currentThread().getId()); int i = 10/2; System.out.println("运行结果:"+i); } } //实现Runnable public static class Runable01 implements Runnable{ @Override public void run(){ System.out.println("当前线程:"+Thread.currentThread().getId()); int i = 10/2; System.out.println("运行结果:"+i); } } //实现Callable public static class Callable01 implements Callable<Integer>{ @Override public Integer call() throws Exception { System.out.println("当前线程:"+Thread.currentThread().getId()); int i = 10/2; return i; } } }
2、线程池的七大参数
* @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 拒绝策略,如果线程满了,线程池就会使用拒绝策略。
原生方式创建线程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 200, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
运行流程:
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 个默认拒绝策略。
3、常见的 4 种线程池
- newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若
无可回收,则新建线程。
- newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
- newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。
- newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务
按照指定顺序(FIFO, LIFO, 优先级)执行。
4、开发中为什么使用线程池
- 降低资源的消耗
通过重复利用已经创建好的线程降低线程的创建和销毁带来的损耗
- 提高响应速度
因为线程池中的线程数没有超过线程池的最大上限时,有的线程处于等待分配任务
的状态,当任务来时无需创建新的线程就能执行
- 提高线程的可管理性
线程池会根据当前系统特点对池内的线程进行优化处理,减少创建和销毁线程带来
的系统开销。无限的创建
二、CompletableFuture 异步编排
业务场景:
查询商品详情页的逻辑比较复杂,有些数据还需要远程调用,必然需要花费更多的时间。
假如商品详情页的每个查询,需要如下标注的时间才能完成
那么,用户需要 5.5s 后才能看到商品详情页的内容。很显然是不能接受的。
如果有多个线程同时完成这 6 步操作,也许只需要 1.5s 即可完成响应。
CompletableFuture 和 FutureTask 同属于 Future 接口的实现类,都可以获取线程的执行结果。
1、创建异步对象
CompletableFuture 提供了四个静态方法来创建一个异步操作。
1、runXxxx 都是没有返回结果的,supplyXxx 都是可以获取返回结果的
2、可以传入自定义的线程池(通常使用),否则就用默认的线程池;
2、计算完成时回调方法
whenComplete 可以处理正常和异常的计算结果,exceptionally 处理异常情况。
whenComplete 和 whenCompleteAsync 的区别:
- whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。
- whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。
方法不以 Async 结尾,意味着 Action 使用相同的线程执行,而 Async 可能会使用其他线程
执行(如果是使用相同的线程池,也可能会被同一个线程选中执行)
CompletableFuture.supplyAsync(()->{ int i = 10 / 0; return i; },executorService).whenComplete((res,excption)->{ //虽然能得到异常信息,但是无法修改返回数据。 System.out.println("异常任务成功完成了...结果是:"+res+";异常是"+excption); }).exceptionally(throwable -> { //可以感知异常,同时返回默认值 return 10; });
3、handle 方法
和 complete 一样,可对结果做最后的处理(可处理异常),可改变返回值。
CompletableFuture.supplyAsync(()->{ int i = 10 / 0; return i; },executorService).handle((res,excetion)->{ if (res!=null){ return res*2; } if (excetion!=null){ return 0; } return 0; });
4、线程串行化方法
thenApply 方法:当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前任务的返回值。
thenAccept 方法:消费处理结果。接收任务的处理结果,并消费处理,无返回结果。
thenRun 方法:只要上面的任务执行完成,就开始执行 thenRun,只是处理完任务后,执行thenRun 的后续操作
带有 Async 默认是异步执行的。同之前。
以上都要前置任务成功完成。
Function<? super T,? extends U>
T:上一个任务返回结果的类型 U:当前任务的返回值类型
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { int i = 10 / 0; return i; }, executorService).thenApplyAsync(res -> { //res是上边任务执行的结果 System.out.println("任务2启动了。。。" + res); return "hello" + res; }, executorService); System.out.println(future.get());
5、两任务组合 - 都要完成
两个任务必须都完成,触发该任务。
runAfterBoth:组合两个 future,不需要获取 future 的结果,只需两个 future 处理完任务后,处理该任务。
thenAcceptBoth:组合两个 future,获取两个 future 任务的返回结果,然后处理任务,没有返回值。
thenCombine:组合两个 future,获取两个 future 的返回结果,并返回当前任务的返回值
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> { int i = 10 / 0; return i; }, executorService); CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> { return "Hello"; }, executorService); //无返回值 // future01.runAfterBothAsync(future02,()->{ // System.out.println("任务3"); // },executorService); //能接收f1,f2返回结果,自身无返回值 // future01.thenAcceptBothAsync(future02,(f1,f2)->{ // System.out.println("任务3:"+f1+f2); // },executorService); //能接收f1,f2返回结果,自身有返回值 CompletableFuture<String> future03 = future01.thenCombineAsync(future02, (f1, f2) -> { return f1 + f2; }, executorService); System.out.println(future03.get());
6、两任务组合 - 一个完成
当两个任务中,任意一个 future 任务完成的时候,执行任务。
runAfterEither:两个任务有一个执行完成,不需要获取 future 的结果,处理任务,也没有返回值。
acceptEither:两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值。
applyToEither:两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值。
CompletableFuture<String> future03 = future01.applyToEitherAsync(future02, res -> { return res.toString() + "任务3"; }, executorService);
7、多任务组合(常用)
allOf:等待所有任务完成
anyOf:只要有一个任务完成
CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future01, future02); completableFuture.get();//等待所有任务执行完才继续执行后续代码
8、使用案例
线程池配置的配置引入
@ConfigurationProperties(prefix = "gulimall.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
private Integer coreSize;
private Integer maxSize;
private Integer keepAliveTime;
}
在application.properties中添加配置
gulimall.thread.core-size=20
gulimall.thread.max-size=200
gulimall.thread.keep-alive-time=10
线程池配置
//ThreadPoolConfigProperties已使用@Component,可以直接注入使用,则无需再使用@EnableConfigurationProperties
// @EnableConfigurationProperties(ThreadPoolConfigProperties.class)
@Configuration
public class MyThreadConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties pool){
return new ThreadPoolExecutor(
pool.getCoreSize(),
pool.getMaxSize(),
pool.getKeepAliveTime(),
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
}
}
线程池使用
@Autowired
ThreadPoolExecutor executor;
@Override
public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
SkuItemVo skuItemVo = new SkuItemVo();
CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
//1、sku基本信息获取 pms_sku_info
SkuInfoEntity info = getById(skuId);
skuItemVo.setInfo(info);
return info;
}, executor);
// Long spuId = info.getSpuId();
// Long catalogId = info.getCatalogId();
CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
//3、获取spu的销售属性组合。
List<SkuItemVo.SkuItemSaleAttrVo> saleAttrVos =
skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
skuItemVo.setSaleAttr(saleAttrVos);
}, executor);
CompletableFuture<Void> descFutire = infoFuture.thenAcceptAsync((res) -> {
//4、获取spu介绍
SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
skuItemVo.setDesp(spuInfoDescEntity);
}, executor);
CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
//5、获取spu的规格参数信息
List<SkuItemVo.SpuItemAttrGroupVo> attrGroupVos =
attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
skuItemVo.setGroupAttrs(attrGroupVos);
}, executor);
//2、sku图片信息
CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
skuItemVo.setImages(images);
}, executor);
//3、查询当前sku是否参与秒杀优惠
//等待所有任务都完成
CompletableFuture.allOf(saleAttrFuture,descFutire,baseAttrFuture,imageFuture).get();
return skuItemVo;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?