Fork/join
The Fork/join in JAVA7, similar to the mapreduce idea of Distributed File System Hadoop, is to split the task, then split it, until it is partitioned to meet the conditions
For ease of understanding: The programming logic can borrow the idea of recursion, the layer of recursion, until the final tune, and then return to the layer, and in the Fork/join is, like each recursive method, put in a single thread;
Leverage modern multicore processors for parallel processing of tasks
Such as:
/*** Inherit recursivetask each subtask with return value * Inherits recursiveaction each subtask has no return value*/ Public classFockJoin1extendsRecursivetask<integer>{ Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {LongL =System.currenttimemillis (); Forkjoinpool Pool=NewForkjoinpool ();//similar to the thread pool, it also implements the AbstractexecutorserviceFockJoin1 task =NewFockJoin1 (1,1000000000);//New Taskfuture<integer> result = Pool.submit (Task);//Submit a TaskSYSTEM.OUT.PRINTLN ("result is" + result.get ());//Get ResultsSystem.err.println (System.currenttimemillis ()-l); } Private FinalInteger index = 5000;//the cardinality of the split task Private FinalInteger left; Private FinalInteger right; PublicFockJoin1 (integer left, integer right) { This. left =Left ; This. right =Right ; } @OverrideprotectedInteger Compute () {intsum = 0; if(Right-left < index) {//if the task is less than the cardinality, it is executed directly; like a recursive exit for(inti = left; I <= right; i++) {sum+=i; } }Else{//tasks larger than cardinality, then split, similar to dichotomy, can also be more intMiddle = (right + left) >> 1; FockJoin1 Myf1=NewFockJoin1 (left, middle);//To the left of dichotomyFockJoin1 myf2=NewFockJoin1 (middle+1, right);//right of dichotomyMyf1.fork ();//continue execution, similar to recursionMyf2.fork ();//continue execution, similar to recursionInteger integer1 = Myf1.join ();//waitInteger Integer2 =Myf2.join (); Sum= Integer1 + integer2;//result Merge } returnsum; }}
Java Concurrency Programming (fork/join)