1
0

更新 Java_3-5.md

This commit is contained in:
8ga 2025-09-11 09:45:19 +08:00
parent a911c16787
commit 4765d00610

View File

@ -1,7 +1,7 @@
### 问题1考察多线程
**问题内容**
<p style="color: red">
假设你现在需要写1个电商APP的用户订单详情接口这个详情页包含
- 关联的商品信息,比如商品名称、尺码、图片、文字介绍等等
@ -9,16 +9,19 @@
- 订单的快递信息,比如从上海运往杭州,目前运输车辆的位置
这三种数据彼此之间不耦合假定每一个查询耗时1秒单线程的情况下同步执行三次查询则需要3秒如何加速这个查询
</p>
**问题答案**
<p style="color: green">
答案:多线程并行查询
</p>
**继续追问**
<span style="color: red">
<p style="color: red">
假定有3个Runnable对象分别是task1、task2、task3作为查询函数对象如何调度或者编排这3个task
</span>
</p>
```
Runnable task1 = () -> System.out.println("Task 1");
@ -28,9 +31,9 @@ Runnable task3 = () -> System.out.println("Task 3");
**方案一、CompletableFuture**
<span style="color: green">
使用 CompletableFuture 的 runAsync 函数声明3个异步任务。通过 CompletableFuture 的 allOf 函数添加3个异步任务调用 get 函数阻塞
</span>
<p style="color: green">
使用 CompletableFuture 的 runAsync 函数包装3个task。再通过 allOf 函数添加3个task调用 get 函数阻塞等待3个任务执行完毕
</p>
```
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(task1);
@ -41,14 +44,15 @@ CompletableFuture.allOf(cf1, cf2, cf3).get();
**方案二、Future**或者**FutureTask**
<p style="color: green">
把3个task提交给1个自定义线程池并接收Future对象再使用get函数等待3个任务执行完毕
</p>
```
// 使用自定义线程池
ExecutorService executor = Executors.newFixedThreadPool(3);
// 把这3个任务提交给线程池并行执行
Future<Void> f1 = executor.submit(task1);
Future<Void> f2 = executor.submit(task2);
Future<Void> f3 = executor.submit(task3);
// 使用get函数等待3个任务执行完毕
f1.get();
f2.get();
f3.get();
@ -56,8 +60,11 @@ f3.get();
**如果回答的是CompletableFuture继续延伸以下问题**
- CompletableFuture的默认线程池是什么答案ForkJoinPool
- ForkJoinPool适合CPU密集型还是IO密集型任务答案CPU密集型
- 用CompletableFuture处理IO密集型的任务应该怎么做答案自定义一个IO密集型的线程池
<p style="color: red">CompletableFuture的默认线程池是什么</p>
<p style="color: green">答案ForkJoinPool</p>
<p style="color: red">ForkJoinPool适合CPU密集型还是IO密集型任务</p>
<p style="color: green">答案CPU密集型</p>
<p style="color: red">用CompletableFuture处理IO密集型的任务应该怎么做</p>
<p style="color: green">答案自定义一个IO密集型的线程池</p>
### 问题2考察对Mybatis-Plus或者Mybatis框架的熟练度