A simple example of Java-Fork/Join
Content: explanation on the Internet:
Step 1: Split the task. First, we need a fork class to split large tasks into subtasks. It is possible that the subtasks are still large, so we still need to keep splitting until the subtasks are small enough.
Step 2: Execute the task and merge the results. Separate sub-tasks are placed in the double-end queue, and then several start threads obtain the task execution from the double-end queue respectively. All the results of sub-tasks are stored in a queue. Start a thread to fetch data from the queue and merge the data.
Public class CountTaskTmp extends RecursiveTask
{Private static final int THRESHOLD = 2; private int start; private 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 value, split into two subtasks to calculate int mid = (start + end)/2; CountTask leftTask = new CountTask (start, mid); CountTask rightTask = new CountTask (mid + 1, end); // execute the subtask leftTask. fork (); rightTask. fork (); // wait until the sub-task is executed and the result int leftResult = (int) leftTask is obtained. join (); int rightResult = (int) rightTask. join (); sum = leftResult + rightResult;} return sum;} public static void main (String [] args) {ForkJoinPool forkJoinPool = new ForkJoinPool (); // generate a computing qualification and calculate 1 + 2 + 3 + 4 CountTask task = new CountTask (1, 4); Future
Result = forkJoinPool. submit (task); try {System. out. println (result. get ();} catch (Exception e ){}}}