A simple example of Java-Fork/Join

Source: Internet
Author: User

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 ){}}}
  
 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.