Package thread;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ForkJoinPool;
Import Java.util.concurrent.Future;
Import Java.util.concurrent.RecursiveTask;
/**
* Fork/join Framework for Multithreaded computing <br/>
* Calculate the sum of 1+2+3+4+...+99+100 <br/>
* Because this program simulates the simplest calculation, it takes very little time, so multithreading is not as fast as a single-threaded calculation. <br/>
* But if it's more time-consuming and complex, multithreaded computing is much faster!
* @author Zhaoyujie
*
*/
public class Counttask extends Recursivetask<integer> {
Private static final long serialversionuid = -4488036422261690638l;
private static final int THRESHOLD = 10;
private int start;
private int end;
Public counttask (int start, int end) {
This.start = start;
This.end = end;
}
@Override
Protected Integer Compute () {
int sum = 0;
Calculate tasks If the task is small enough
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, it will split into two sub-task calculations
int middle = (start+end)/2;
Counttask lefttask = new Counttask (start, middle);
Counttask righttask = new Counttask (middle+1, end);
Lefttask.fork ();
Righttask.fork ();
Wait for the subtasks to finish and get their results
int leftresult = Lefttask.join ();
int rightresult = Righttask.join ();
sum = Leftresult + Rightresult;
}
return sum;
}
public static void Main (string[] args) {
Long currtime = System.currenttimemillis ();
Forkjoinpool Forkjoinpool = new Forkjoinpool ();
Counttask task = new Counttask (1, 100);
future<integer> future = Forkjoinpool.submit (Task);
try {
System.out.println (Future.get ());
System.out.println ("spents milliseconds:" + (System.currenttimemillis ()-currtime));
} catch (Interruptedexception e) {
E.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();
}
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Split a complex large task into several simple small tasks for calculation