1
0
md/Java_3-5.md
2025-09-11 09:45:19 +08:00

71 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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