更新 Java_3-5.md
This commit is contained in:
parent
a911c16787
commit
4765d00610
31
Java_3-5.md
31
Java_3-5.md
@ -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框架的熟练度)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user