# Java里简单快速实现并行操作

{% embed url="<https://v.douyin.com/r8Nqwdm/>" %}

{% embed url="<https://www.bilibili.com/video/BV1yG41187CQ/>" %}

在这个controller里边

这3个方法是模拟了3个查询

他们分别会耗时几百毫秒

那问题是什么呢

现在是

这3个查询其实没有任何依赖关系

就是说你想先查谁就

先查谁

最后只要把他们3个都查出来就行了

但现在这样写的话呢他们就是串行的

也就说查完1、再查2、再查

总耗时就是他们三个加一起

后来呢我就想到了

能不能模仿这个JS里的Promise

封装这么一个方法

我给他加了一个olit

这样的话呢这三个字任务就会

并行的去

执行

等最慢的那个执行完之后呢

这个方法就走完了

不过我发现

原来啊 JDK 1.8里边（往后）

他有默认的（方式）支持了这种类似的方法

就是这个CompletableFuture

allOf 然后里边还是用这个点runAsync

来创建子任务

但是呢

这里面最好我们自己准备一个线程池

你不准备这个线程池也可以

他用的就是一个公用的现成池

那个现成池就不太适合

带I/O的这种操作

他就比较适合

计算密集型的任务

所以呢我准备了一个线程池，这样来执行

我们来看一下这3个的效果哈

我们先来第一个大家看

比较慢是吧

我们再看第2个

明显就会快了

我们再看第3个

一样的


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sunzsh.gitbook.io/xiaoshan.bug/java-li-jian-dan-kuai-su-shi-xian-bing-xing-cao-zuo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
