> For the complete documentation index, see [llms.txt](https://tuonioooo-notebook.gitbook.io/java-concurrent/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tuonioooo-notebook.gitbook.io/java-concurrent/forkjoinkuang-jia/forkjoinkuang-jia-de-she-ji.md).

# Fork/Join框架的设计

我们已经很清楚Fork/Join框架的需求了，那么可以思考一下，如果让我们来设计一个

Fork/Join框架，该如何设计？这个思考有助于你理解Fork/Join框架的设计。

步骤1 分割任务。首先我们需要有一个fork类来把大任务分割成子任务，有可能子任务还

是很大，所以还需要不停地分割，直到分割出的子任务足够小。

步骤2 执行任务并合并结果。分割的子任务分别放在双端队列里，然后几个启动线程分

别从双端队列里获取任务执行。子任务执行完的结果都统一放在一个队列里，启动一个线程

从队列里拿数据，然后合并这些数据。

Fork/Join使用两个类来完成以上两件事情。

①ForkJoinTask：我们要使用ForkJoin框架，必须首先创建一个ForkJoin任务。它提供在任务

中执行fork()和join()操作的机制。通常情况下，我们不需要直接继承ForkJoinTask类，只需要继

承它的子类，Fork/Join框架提供了以下两个子类。

·RecursiveAction：用于没有返回结果的任务。

·RecursiveTask：用于有返回结果的任务。

②ForkJoinPool：ForkJoinTask需要通过ForkJoinPool来执行。

任务分割出的子任务会添加到当前工作线程所维护的双端队列中，进入队列的头部。当

一个工作线程的队列里暂时没有任务时，它会随机从其他工作线程的队列的尾部获取一个任

务。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://tuonioooo-notebook.gitbook.io/java-concurrent/forkjoinkuang-jia/forkjoinkuang-jia-de-she-ji.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
