Java asynchronously computes the use of the Future (RPM)

Source: Internet
Author: User

Starting from jdk1.5 we can use the future to track the results of asynchronous computations. Before this, the main thread to get the result of working thread (asynchronous compute thread) is a troublesome thing, we need to make a special program structure design, more cumbersome and error prone. With the future, we can design a more elegant model of asynchronous computational programming: According to the idea of divide and conquer, we can divide the thread of asynchronous computation into 3 categories according to responsibilities:

1. Asynchronous compute Initiation Thread (Control thread): responsible for the decomposition and initiation of the asynchronous computing task, the decomposition of the task to the asynchronous computation of the work thread to execute, after initiating the asynchronous computation, the initiator thread can obtain the Futrue collection, so as to track the asynchronous calculation results

2. Compute work Threads asynchronously: responsible for specific computing tasks

3. Asynchronously computes the result collection thread: Obtains a future collection from the originating thread, and is responsible for monitoring the status of the future, processing the results of the asynchronous computations according to the future state.

Here is an example I wrote based on the above idea:

 PackageCom.chengxuyuanzhilu.two;Importjava.util.List;Importjava.util.concurrent.Future; Public classOutputresultImplementsRunnable {PrivateFuturecontext<string>context;  Public voidSetfuturecontext (futurecontext<string>context) {         This. Context =context; } @Override Public voidrun () {System.out.println ("Start to output result:"); List<Future<String>> list = This. Context.getfuturelist ();  for(future<string>future:list) {             This. Outputresultfromfuture (future); } System.out.println ("Finish to output result."); }        Private voidOutputresultfromfuture (future<string>Future ) {        Try {             while(true) {                if(Future.isdone () &&!future.iscancelled ()) {System.out.println ("Future: + Future +", Result: "+future.get ());  Break; }Else{Thread.Sleep (1000); }            }        } Catch(Exception e) {e.printstacktrace ();    }; }}
 PackageCom.chengxuyuanzhilu.two;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.Future; Public classFuturecontext<t> {    PrivateList<future<t>> futurelist =NewArraylist<>();  Public  voidAddfuture (future<t>Future ) {         This. Futurelist.add (future); }         PublicList<future<t>>getfuturelist () {return  This. futurelist; }}
 PackageCom.chengxuyuanzhilu.two;ImportJava.util.Random;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classAsynccontroller {//thread Pool    PrivateExecutorservice Executorservice; //Save the future of asynchronous computing    PrivateFuturecontext<string>context;  PublicAsynccontroller () {//Create a fixed-size thread pool         This. Executorservice = Executors.newfixedthreadpool (100);  This. Context =NewFuturecontext<>(); }         Public Static voidMain (string[] args) {//start an asynchronous calculationAsynccontroller Controller =NewAsynccontroller ();                Controller.startasyccompution (); //initiates an asynchronous evaluation result output thread that scans the state of the asynchronous compute Futrue and, if completed, outputs the asynchronous calculation resultOutputresult output =NewOutputresult ();        Output.setfuturecontext (Controller.getfuturecontext ()); Thread Resultthread=NewThread (output);    Resultthread.start (); }         PublicFuturecontext<string>Getfuturecontext () {return  This. Context; }         Public voidstartasyccompution () {/*** Open 100 asynchronous computations, each asynchronous compute thread randomly sleep a few seconds to simulate the time-consuming calculation*/        FinalRandom random =NewRandom ();  for(inti = 0; I < 100; i++) { future<String> future = This. Executorservice.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {intRandomint = Random.nextint (10); Thread.Sleep (Randomint* 1000); return"" +Randomint;            }                                            }); //The results of each asynchronous calculation are stored in the context             This. Context.addfuture (future); }    }}

Source: Http://pan.baidu.com/s/1c1uuq5M

Java asynchronously computes the use of the Future (RPM)

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.