This example is to decompose a large array of sums of large tasks into small tasks that are summed in small areas, and then add together these small tasks to the result.
Technology: JDK8.0, Recursivetask technology in Java fork-join mode, override Compute ().
[Java]View Plaincopy print?
- /**
- * Author:bigtree
- * This example is the large task of summing up a large array into small tasks that sum in small sums, and then adding up the sum of these small tasks is the result of the calculation.
- Technology
- * Recursivetask technology in Java fork-join mode, override Compute ().
- */
- Import java.util.*;
- Import java.util.concurrent.*;
- Class Caltask extends recursivetask<long>{
- private static final int THRESHOLD = 1000; //how Many numbers one thread can calculate
- private long data[];
- private int start;
- private int end;
- Public Caltask (long[] inputdata,int start, int end) {
- Data=inputdata;
- This.start=start;
- This.end=end;
- }
- @Override
- protected Long Compute () {
- Long sumresult=0l;
- if ((End-start) <= THRESHOLD) {
- For (int index=start; index<end;index++) {
- Sumresult + = Data[index];
- }
- }
- else { //parallel computing
- int step= (end-start)/threshold;
- if (((End-start)%threshold) >0)
- step+=1;
- arraylist<caltask> tasks = new arraylist<> ();
- int Pos=start;
- int lastposition;
- For (int i=0;i<step;i++) {
- Lastposition=pos+threshold;
- if (lastposition>end)
- Lastposition=end;
- Caltask onetask= New Caltask (data,pos,lastposition);
- Pos=lastposition;
- Tasks.add (OneTask);
- Onetask.fork ();
- }
- For (Caltask mtask:tasks) {
- Sumresult + = Mtask.join ();
- }
- }
- return sumresult;
- }
- }
- public class Forkjoincompute {
- public static void Forkjoinshow () {
- long data[] = new long[20001];
- For (long i=0;i<data.length;i++) {
- data[(int) i]= i + 1;
- }
- Forkjoinpool mypool= Forkjoinpool.commonpool ();
- future<long> myfuture = Mypool.submit ( new Caltask (data,0,data.length));
- try{
- long Result=myfuture.get ();
- System.out.println ("Forkjoincompute (): Computed final result=" +result);
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- } catch (Executionexception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- Mypool.shutdown ();
- }
- }
[Java]View Plaincopy print?
Output Result:
Forkjoincompute (): Computed final result=200030001
Java Fork Join Forkjoinpool Usage Example