Multithreaded programming (vi)--callable&future

Source: Internet
Author: User

Thread Classes and Runnable Interfaces and Java The memory management model makes multithreaded programming straightforward. However , neither the Thread class nor the Runnable interface allow the declaration of a check-type exception, nor can it define a return value.

callable Interfaces and Future The introduction of interfaces and their support for the thread pool elegantly address these two issues.

           callable interface similar to Span lang= "en-US" style= "Font-family:calibri" >runnable interface, callable After the interface is executed by the thread, the value can be returned, and the return value can be future get, i.e., future can get the return value of the asynchronous execution task. future Result types obtained and callable The returned result types must be identical, which is achieved by generics.

1, callableto useExecutorserviceof theSubmitmethod Commits, returns the Futureobject can cancel a task

Code:

public static void Main (string[] args) {Executorservice threadPool = Executors.newsinglethreadexecutor ();// Submit is submitted to return the result future<string> future = Threadpool.submit (new callable<string> () {public String call () Throws Exception {Thread.Sleep (+); return "Hello";};}); System.out.println ("Wait for results"); try {System.out.println ("Get Result:" + Future.get ())} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();} catch (Executionexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}

Results:


Executor so that we do not need to show to manage the life cycle of threads.

2. Perform multiple tasks with return values and get multiple return values


  Mode 2 Completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task//As I planted several plots of wheat at the same time, and then waited for the harvest. When the harvest is ripe, it is the first to reap the wheat. Executorservice threadPool2 = Executors.newfixedthreadpool (10); completionservice<integer> compeletionservice = new executorcompletionservice<integer> (threadPool2); for (int i = 0; I <=; i++) {final int seq = i;compeletionservice.submit (new callable<integer> () {@Overridepubl IC Integer Call () throws Exception {Thread.Sleep (New Random (). Nextint (); return seq;}});} for (int i = 0; i <; i++) {try {//Generate thread, return the result and bring back the result System.out.println (Compeletionservice.take (). get ());} catch (Inter Ruptedexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Executionexception e) {//Todo Auto-gen Erated catch Blocke.printstacktrace ();}}


Results:



3, understand the callable interface and the future interface


callable interface and Runnable the difference between interfaces

      1) callable When defining a method call runnable The method of definition is run

      2) callable call The method can be returned by a value, and runnable run method cannot have a return value

3) Callable of the Pager method can throw an exception, and Runnable of the Run methods cannot throw exceptions

           future represents the results of one-step calculations, It provides a way to check whether the calculation is complete, to wait for the completion of the calculation, and to retrieve the results of the calculation. future calcel method can cancel the execution of a task, it has a Boolean parameter, the parameter is true false future get Method waits for the calculation to complete and gets the result of the calculation.

Multithreaded Programming (vi)--callable&future

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.