From the Concurrent programming network: HTTP://IFEVE.COM/FORK-JOIN-3/
If the task must resolve a problem that exceeds the predefined size, you should break the task down into more subtasks and use the Fork/join framework to perform these subtasks. When these subtasks are completed, the resulting task will get the results from all subtasks, group the results, and return the final result. Eventually, when the initiated task in the pool completes its execution, you will get the end result of the entire problem.
1, create a two-dimensional array simulation document:
Package Com.wenbronk.forkjoin.withresult;import java.util.Random;/** * Created by Wenbronk on 2017/7/26.*/ Public classDocument {PrivateString words[] = {" the","Hello","Goodbye","Pack","Java","Thread","Pool","Random","class","Main"}; PublicString[][] Generatedocument (intNumlines,intnumwords, String Word) { intCounter =0; String[][] Document=NewString[numlines][numwords]; Random Random=NewRandom (); //populating an array for(intI=0; i<numlines; i++){ for(intj=0; j<numwords; J + +) { intindex=Random.nextint (words.length); DOCUMENT[I][J]=Words[index]; if(Document[i][j].equals (Word)) {counter++; }}} System. out. println (Document.length +": "+ Document[document.length-1].length); System. out. println ("documentmock:the Word appears"+ Counter +"Times in the document"); returndocument; }}
2, row splitting of the analog document
Package Com.wenbronk.forkjoin.withresult;import Java.util.arraylist;import Java.util.concurrent.executionexception;import Java.util.concurrent.RecursiveTask;/** * Created by Wenbronk on 2017/7/26.*/ Public classDocumenttask extends Recursivetask<integer> { Privatestring[][] document; Private intstart, end; PrivateString Word; PublicDocumenttask (string[][] document,intStartintend, String word) { This. Document =document; This. Start =start; This. end =end; This. Word =Word; } @OverrideprotectedInteger Compute () {intresult =0; if(End-start <Ten) {result=Processlines (document, Start, end, word); } Else { intMid = (start + end)/2; Documenttask Task1=NewDocumenttask (document, Start, Mid, Word); Documenttask Task2=NewDocumenttask (document, Mid, end, word); InvokeAll (Task1, Task2); Try{result= Groupresults (Task1.Get(), Task2.Get()); }Catch(Interruptedexception |executionexception e) {E.printstacktrace (); } } returnresult; } Private intgroupresults (integer integer, integer integer1) {returnInteger +Integer1; } /** * To find the word*/ Private intProcesslines (string[][] document,intStartintend, String word) {ArrayList<LineTask> tasks =NewArraylist<>(); for(inti = start; I < end; i++) {Linetask linetask=NewLinetask (Document[i],0, document[i].length, Word); Tasks.add (Linetask); } invokeall (tasks); intresult =0;//For (Linetask task:tasks) { for(inti =0; I < tasks.size (); i++) {Linetask task= Tasks.Get(i); Try {//Thread.Sleep (+);Result + = task.Get(); } Catch(Exception e) {e.printstacktrace (); } } returnresult; }}
3, Word splitting on lines
Package Com.wenbronk.forkjoin.withresult;import Java.util.concurrent.RecursiveTask;/** * Count the number of occurrences of a word in a line * Created by Wenbronk on 2017/7/27.*/ Public classLinetask extends Recursivetask<integer> { Private StaticFinalLongSeriaversionuid =1L; Privatestring[] Line; Private intstart, end; PrivateString Word; PublicLinetask (string[] line,intStartintend, String word) { This. Line =Line ; This. Start =start; This. end =end; This. Word =Word; } @Overrideprotectedinteger Compute () {integer result=NULL; if(End-start < -) {result=count (line, start, end, word); }Else { intMid = (start + end)/2; Linetask Task1=NewLinetask (line, start, mid, Word); Linetask Task2=NewLinetask (line, Mid, end, word); InvokeAll (Task1, Task2); Try{result= Groupresult (Task1.Get(), Task2.Get()); } Catch(Exception e) {e.printstacktrace (); } } returnresult; } /** * Merge values of 2 values, return results * @return*/ Privateinteger groupresult (integer num1, integer num2) {returnNUM1 +num2; } /** * Find the number of occurrences of word in a row*/ PrivateInteger count (string[] line,intStartintend, String word) { intCounter =0; for(inti = start; I < end; i++) { if(Word.equals (Line[i])) {counter++; } }//try {//Thread.Sleep (ten);//} catch (Exception e) {//e.printstacktrace ();// } returncounter; }}
4, Ingress execution class
Package Com.wenbronk.forkjoin.withresult;import Java.util.concurrent.forkjoinpool;import Java.util.concurrent.TimeUnit;/** * Created by Wenbronk on 2017/7/27.*/ Public classCountmain { Public Static voidMain (string[] args) {Document document=NewDocument (); String[][] Documents= Document.generatedocument ( -, +,"Random"); Documenttask Task=NewDocumenttask (Documents,0, -,"Random"); Forkjoinpool Pool=NewForkjoinpool (); Pool.execute (Task); Do{System. out. printf ("******************************************\n"); System. out. printf ("main:parallelism:%d\n", Pool.getparallelism ()); System. out. printf ("main:active Threads:%d\n", Pool.getactivethreadcount ()); System. out. printf ("main:task Count:%d\n", Pool.getqueuedtaskcount ()); System. out. printf ("main:steal Count:%d\n", Pool.getstealcount ()); System. out. printf ("******************************************\n"); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } } while(!Task.isdone ()); Pool.shutdown (); Try{System. out. printf ("main:the Word appears%d in the document", Task.Get()); } Catch(Exception e) {e.printstacktrace (); } }}
Java-forkjoin with return value