Java concurrency programming from getting started to mastering-the 7th chapter: Fork/join Framework

Source: Internet
Author: User

1, Summary: Simplify, divide and conquer, recursive decomposition and merger, until the task is small to acceptable degree;
2. Future task mechanism:
The future interface is to cancel the execution result of the specific runnable or callable task, whether the query is completed or not, and the result can be obtained by the Get method if necessary, and the method will block until the task returns the result. This means that the future interface provides three functions: to determine whether a task is completed, to interrupt a task, and to get the result of a task execution;
The common method inside the future interface;
3, Futuretask:
The Futuretask class is the only implementation class of the future interface;
The Futuretask class implements the Runnable interface and the future interface, so it can be executed either as a runnable thread, or as a future callable return value;
Two constructors of the Futuretask;

1 /**2 * Use of Futuretask3  */4  Packagethread06;5 6 Importjava.util.concurrent.Callable;7 Importjava.util.concurrent.ExecutionException;8 ImportJava.util.concurrent.FutureTask;9 Ten  Public classFutureTaskTest01 One { A      Public Static voidMain (string[] args)throwsinterruptedexception, Executionexception -     { -Myson Myson =NewMyson ("Thread Son1"); theFuturetask<string> FT1 =NewFuturetask<string>(Myson); -         NewThread (FT1). Start (); -         //if the Get () method is called, then only the returned result will continue to be executed. -         //do not call the Get () method (do not want to get the return result), go straight down + System.out.println (Ft1.get ()); -          +         //executes the specified thread and returns the specified result (.) Afuturetask<integer> ft2 =NewFuturetask<integer> (NewMyrun (), 22); at         NewThread (ft2). Start (); -System.out.println ("Result_" +ft2.get ()); -          -System.out.println ("Thread Main end!"); -     } - } in  - classMysonImplementsCallable<string> to { +     PrivateString name; -      the      PublicMyson (String name) *     { $          This. Name =name;Panax Notoginseng     } -      the @Override +      PublicString Call ()throwsException A     { theThread.Sleep (1000L); +SYSTEM.OUT.PRINTLN (name + "task calculation complete")); -         return"Result_11"; $     } $ } -  - classMyrunImplementsRunnable the { - @OverrideWuyi      Public voidRun () the     { -         Try Wu         { -Thread.Sleep (1000L);//Simulation Work About}Catch(interruptedexception e) $         { - e.printstacktrace (); -         } -          ASYSTEM.OUT.PRINTLN ("Specific thread 2 complete task"); +     } the } -  $ /* the the task implements callable interface, can return the result; the the task implements Runnable interface, can not return the result, but can return the specified result through Futuretask disguise; the */
Use of Futuretask

4. Future use scenario:
Actual work, you may need to count the various types of report rendering results, perhaps a large report needs to rely on the results of many small modules, a thread may be slow, you can split into n multiple small threads, and then merge the results as a large report rendering results; the next fork/ Join is based on the future implementation;
5, what is the Fork/join framework:
is a framework for parallel execution of tasks, a framework that divides large tasks into several small tasks, and ultimately summarizes the results of a large task after each small task .
6, Fork/join's JDK inside the family:
7, the Fork/join Framework implementation principle:
8. Exception handling mechanism and methods:
9. The advantages and disadvantages of fork/join model and its practical application scenario:
Advantages: For applications that conform to Fork/join mode, software developers no longer need to handle a variety of parallel related transactions, such as synchronization, communication, such as the deadlock and data race known for difficult debugging and other errors will not appear, raising the level of thinking issues; parallel distribution strategy, Just focus on how to divide tasks and combine intermediate results, leaving the rest to the Fork/join framework to complete;
Cons: If there are too many objects to be split, be careful to fill up the memory at once, wait for the thread's CPU resources to be freed, but the thread object waits without being recycled by the garbage mechanism;
usage Scenario: the processing and traversal of data for a tree structure type is appropriate;

1 /**2 * Use of the Fork/join framework: Calculate 1+2+3+4+5 Results3  */4  Packagethread06;5 6 Importjava.util.concurrent.ExecutionException;7 ImportJava.util.concurrent.ForkJoinPool;8 Importjava.util.concurrent.Future;9 ImportJava.util.concurrent.RecursiveTask;Ten  One  Public classForkJoinTest01 A { -      Public Static voidMain (string[] args)throwsinterruptedexception, Executionexception -     { theForkjoinpool pool =NewForkjoinpool (); -          -Counttask Task1 =NewCounttask (1, 5); -future<integer> future =Pool.submit (TASK1); +SYSTEM.OUT.PRINTLN ("The result of the final addition of 1-5 is:" +future.get ()); -          +Counttask Task2 =NewCounttask (1, 100); AFuture<integer> Future2 =Pool.submit (TASK2); atSYSTEM.OUT.PRINTLN ("The result of the final addition of 1-100 is:" +future2.get ()); -     } - } -  - classCounttaskextendsRecursivetask<integer> - { in     Private Static Final LongSerialversionuid = 1L; -      to     Private Static intSplitsize = 2; +     Private intstart; -     Private intend; the      *      PublicCounttask (intStartintend) $     {Panax Notoginseng          This. Start =start; -          This. end =end; the     } +      A @Override the     protectedInteger Compute () +     { -         intsum = 0; $          $         //if the task no longer needs to be split, start calculating -         BooleanCancompute = (End-start) <=splitsize; -         if(Cancompute) the         { -             //if it's 1+2+3, this is the branch.Wuyi              for(inti=start;i<=end;i++) the             { -sum = sum +i; Wu             } -         } About         Else $         { -             //split into two sub-tasks -             intMiddle = (start + end)/2; -Counttask Firsttask =Newcounttask (start, middle); ACounttask Secondtask =NewCounttask (middle+1, end); +              the             //when the sub-task calls the Fork method, it also enters the compute method to see if the current subtask needs to continue splitting into a grandchild task. -             //If you do not need to continue splitting, execute the current subtask and return the results $Firsttask.fork ();//Start Calculation the secondtask.fork (); the              the             //Gets the result of the first subtask, no results, and the thread does not execute below the             intFirstresult =Firsttask.join (); -             intSecondresult =Secondtask.join (); in              the             //consolidated results of two sons thesum = Firstresult +Secondresult; About         } the          the         returnsum; the     } +      -}
use of the Fork/join framework: Calculating the results of a 1+2+3+4+5

Java concurrency programming from getting started to mastering-the 7th chapter: Fork/join Framework

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.