Content: Using the online explanation:
The first step is to split the task. First we need to have a fork class to divide the large task into sub-tasks, it is possible that the subtasks are still very large, so it is necessary to continue to split, until the split sub-task is small enough.
The second step executes the task and merges the results. Split subtasks are placed in a double-ended queue, and several boot threads get task execution from the double-ended queue, respectively. The results of the subtasks are uniformly placed in a queue, starting a thread to take the data from the queue, and then merging the data.
public class Counttasktmp extends recursivetask<integer>{private static final int THRESHOLD = 2;private int START;PR ivate int end;public counttasktmp (int start, int end) {This.start = Start;this.end = end;} @Overrideprotected Integer Compute () {int sum = 0;boolean Cancompute = (end-start) <= threshold;if (Cancompute) {for (int i = start; I <= end; i++) sum + = i;} else {//If the task is greater than the threshold, split into two subtasks to calculate int mid = (start + end)/2; Counttask lefttask = new Counttask (start, mid); Counttask righttask = new Counttask (mid+1, end);//Perform subtask lefttask.fork (); Righttask.fork ();//wait for subtask to finish and get result int Leftresult = (int) lefttask.join (), int rightresult = (int) righttask.join (); sum = Leftresult + rightresult;} return sum;} public static void Main (string[] args) {Forkjoinpool forkjoinpool = new Forkjoinpool (); Generate a calculation qualification, responsible for calculating 1+2+3+4 counttask task = new Counttask (1, 4); future<integer> result = Forkjoinpool.submit (Task); try {System.out.println (Result.get ());} catch (Exception e) {}}}
A simple example of java-fork/join