A simple example of java-fork/join

Source: Internet
Author: User

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

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.