1
0
md/Java_3-5.md

71 lines
2.4 KiB
Markdown
Raw Normal View History

2025-09-10 17:13:56 +08:00
### 问题1考察多线程
2025-09-11 09:33:40 +08:00
**问题内容**
2025-09-11 09:45:19 +08:00
<p style="color: red">
2025-09-10 17:13:56 +08:00
假设你现在需要写1个电商APP的用户订单详情接口这个详情页包含
- 关联的商品信息,比如商品名称、尺码、图片、文字介绍等等
- 订单的基础信息,比如创建时间、支付金额
- 订单的快递信息,比如从上海运往杭州,目前运输车辆的位置
这三种数据彼此之间不耦合假定每一个查询耗时1秒单线程的情况下同步执行三次查询则需要3秒如何加速这个查询
2025-09-11 09:45:19 +08:00
</p>
2025-09-10 17:13:56 +08:00
2025-09-11 09:33:40 +08:00
**问题答案**
2025-09-11 09:45:19 +08:00
<p style="color: green">
2025-09-11 09:33:40 +08:00
答案:多线程并行查询
2025-09-11 09:45:19 +08:00
</p>
2025-09-11 09:33:40 +08:00
2025-09-11 09:36:40 +08:00
**继续追问**
2025-09-11 09:33:40 +08:00
2025-09-11 09:45:19 +08:00
<p style="color: red">
2025-09-11 09:38:21 +08:00
假定有3个Runnable对象分别是task1、task2、task3作为查询函数对象如何调度或者编排这3个task
2025-09-11 09:45:19 +08:00
</p>
2025-09-11 09:33:40 +08:00
2025-09-11 09:38:50 +08:00
```
2025-09-11 09:33:40 +08:00
Runnable task1 = () -> System.out.println("Task 1");
Runnable task2 = () -> System.out.println("Task 2");
Runnable task3 = () -> System.out.println("Task 3");
```
2025-09-11 09:34:30 +08:00
**方案一、CompletableFuture**
2025-09-11 09:33:40 +08:00
2025-09-11 09:45:19 +08:00
<p style="color: green">
使用 CompletableFuture 的 runAsync 函数包装3个task。再通过 allOf 函数添加3个task调用 get 函数阻塞等待3个任务执行完毕。
</p>
2025-09-11 09:38:21 +08:00
2025-09-11 09:38:50 +08:00
```
2025-09-11 09:33:40 +08:00
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(task1);
CompletableFuture<Void> cf2 = CompletableFuture.runAsync(task2);
CompletableFuture<Void> cf3 = CompletableFuture.runAsync(task3);
CompletableFuture.allOf(cf1, cf2, cf3).get();
```
2025-09-11 09:34:30 +08:00
**方案二、Future**或者**FutureTask**
2025-09-10 17:13:56 +08:00
2025-09-11 09:45:19 +08:00
<p style="color: green">
把3个task提交给1个自定义线程池并接收Future对象再使用get函数等待3个任务执行完毕
</p>
2025-09-11 09:38:50 +08:00
```
2025-09-11 09:33:40 +08:00
ExecutorService executor = Executors.newFixedThreadPool(3);
Future<Void> f1 = executor.submit(task1);
Future<Void> f2 = executor.submit(task2);
Future<Void> f3 = executor.submit(task3);
f1.get();
f2.get();
f3.get();
```
2025-09-10 17:13:56 +08:00
2025-09-11 09:33:40 +08:00
**如果回答的是CompletableFuture继续延伸以下问题**
2025-09-10 17:13:56 +08:00
2025-09-11 09:45:19 +08:00
<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>
2025-09-10 17:13:56 +08:00
### 问题2考察对Mybatis-Plus或者Mybatis框架的熟练度