Java acquires multi-threaded task results asynchronously using future

Source: Internet
Author: User
Tags rand

The future interface is part of the Java Standard API in the Java.util.concurrent package. The future interface is the implementation of the Java thread's future pattern, which can be computed asynchronously.

With the future, you can do three-segment programming, 1. Start a multithreaded Task 2. Handle other things 3. Collect multi-threaded task results. This enables non-blocking task invocation. The problem encountered on the way is that although the results can be obtained asynchronously, the result of the future needs to be judged by Isdone, or by using the Get () function to block the execution result. This will not be able to track the result status of other threads in real-time, so use get or be cautious, preferably with isdone to use.

Here's a better way to achieve a timely approach to the results of any one thread's completion: Using Completionservice, it adds a blocking queue inside it to get the values from the future and then handles the corresponding processing based on the return value. The two test cases used in general future use and Completionservice are as follows:

Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Random;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Multi-threaded execution, asynchronous get results * *@authorI-clarechen **/ Public classAsyncthread { Public Static voidMain (string[] args) {Asyncthread T=NewAsyncthread (); List<Future<String>> futurelist =NewArraylist<future<string>>(); T.generate (3, futurelist);        T.dootherthings ();    T.getresult (futurelist); }    /*** Generate a specified number of threads, all into the future array * *@paramThreadnum *@paramflist*/     Public voidGenerateintThreadnum, list<future<string>>flist) {Executorservice Service=Executors.newfixedthreadpool (threadnum);  for(inti = 0; i < threadnum; i++) { future<String> f =Service.submit (Getjob (i));        Flist.add (f);    } service.shutdown (); }    /*** Other things*/     Public voiddootherthings () {Try {             for(inti = 0; I < 3; i++) {System.out.println ("Do thing no:" +i); Thread.Sleep (1000 * (NewRandom (). Nextint (10))); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }    /*** Get thread results from future, print results * *@paramflist*/     Public voidGetResult (list<future<string>>flist) {Executorservice Service=Executors.newsinglethreadexecutor ();        Service.execute (Getcollectjob (flist));    Service.shutdown (); }    /*** Generate thread object with specified ordinal * *@paramI *@return     */     PublicCallable<string> Getjob (Final inti) {Final intTime =NewRandom (). Nextint (10); return NewCallable<string>() {@Override PublicString Call ()throwsException {thread.sleep (1000 *Time ); return"Thread-" +i;    }        }; }    /*** Generate result Collection Thread Object * *@paramFlist *@return     */     PublicRunnable Getcollectjob (FinalList<future<string>>flist) {        return NewRunnable () { Public voidrun () { for(future<string>future:flist) {                    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 ();    }                }            }        }; }}

The run results are printed in the same order as the future is placed in the list, for 0,1,2:

Do thing no:0 does thing no:1 do thing no:2  future:[email Protected],result:thread-0future:[email protected],result:thread-1future:[ Email protected],result:thread-2

Here are the scenarios for line enters upgradeable processing that is performed first:

ImportJava.util.Random;ImportJava.util.concurrent.BlockingQueue;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.CompletionService;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorCompletionService;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.LinkedBlockingDeque; Public classtestcallable { Public Static voidMain (string[] args) {Try{completionservicecount (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }    }      /*** Collect callable results using Completionservice *@throwsexecutionexception *@throwsinterruptedexception*/     Public Static voidCompletionservicecount ()throwsinterruptedexception, executionexception {executorservice executorservice=Executors.newcachedthreadpool (); Completionservice<Integer> Completionservice =NewExecutorcompletionservice<integer>(Executorservice); intThreadnum = 5;  for(inti = 0; i < threadnum; i++) {Completionservice.submit (Gettask (i)); }        intsum = 0; inttemp = 0;  for(inti=0;i<threadnum;i++) {Temp=Completionservice.take (). get (); Sum+=temp; System.out.print (Temp+ "\ T"); } System.out.println ("Completionservice All is:" +sum);    Executorservice.shutdown (); }     Public StaticCallable<integer> Gettask (Final intNO) {        FinalRandom Rand =NewRandom (); Callable<Integer> task =NewCallable<integer>() {@Override PublicInteger Call ()throwsException {intTime = rand.nextint (100) *100; System.out.println ("Thead:" +no+ "time is:" +Time );                Thread.Sleep (time); returnNo;        }        }; returntask; }}

The result of the thread that runs the result is first processed:

Thead0  Timeis:4200thead:1  Timeis:6900thead:2  Timeis:2900thead:3  Timeis:9000thead:4  Timeis:71002    0    1    4    3Completionservice All is:Ten

Java acquires multi-threaded task results asynchronously using future

Related Article

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.