Introduction of callable and future

Source: Internet
Author: User

Introduction of callable and future

     callable and   future  The two functions are added in subsequent versions of Java in order to accommodate multiple concurrency, callable is similar to the Runnable interface, the class that implements callable interface and the class that implements runnable are all tasks that can be performed by other threads. The interface definition for

Callable is as follows;

 public   callable<v> {V call ()  throws   Exception;}  
The differences between

callable and runnable are as follows:

I    callable is defined by call, and the method defined by Runnable is run. The call method for

II   callable can have a return value, and the runnable run method cannot have a return value. The call method of the

III  callable throws an exception, and the runnable run method cannot throw an exception.  

Future Introduction

Future represents the result of an asynchronous calculation that 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. The Cancel method of the future can cancel the execution of a task, it has a Boolean parameter, the parameter is true to immediately interrupt the execution of the task, the parameter is false to allow the running task to run complete. The Get method of the future waits for the calculation to complete and gets the result

 

Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Callable and future interfaces * Callable are similar to runnable interfaces, classes that implement callable interfaces, and classes that implement runnable, are tasks that can be performed by other threads. * There are several differences between callable and runnable: * (1) The method prescribed by callable is call (), and the Runnable method is run (). * (2) callable can return a value after a task is executed, and Runnable's task cannot return a value. * (3) The call () method throws an exception, and the run () method cannot throw an exception. * (4) Run the callable task to get a future object, * the future represents the result of an asynchronous calculation. 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. * The future object can be used to understand task execution, cancel the execution of the task, and get the result of the task execution. */ Public classCallableandfuture { Public Static classMycallableImplementscallable{Private intFlag = 0;  PublicMycallable (intflag) This. Flag =Flag; }           PublicString Call ()throwsexception{if( This. Flag = = 0){                        return"Flag = 0"; }             if( This. Flag = = 1){                   Try {                     while(true) {System.out.println ("Looping."); Thread.Sleep (2000); }                } Catch(interruptedexception e) {System.out.println ("Interrupted"); }                return"False"; } Else {                          Throw NewException ("Bad flag value!"); }        }    }     Public Static voidMain (string[] args) {//define tasks for 3 callable typesmycallable Task1=NewMycallable (0); Mycallable Task2=NewMycallable (1); Mycallable Task3=NewMycallable (2); //Create a service that performs a taskexecutorservice es= Executors.newfixedthreadpool (3); Try {           //Submit and execute a task, and a future object is returned when the task starts .//If you want the result of a task execution or an exception, you can manipulate the future object.Future Future1=Es.submit (TASK1); //Gets the result of the first task, and if the Get method is called, the current thread waits until the task finishes executingSystem.out.println ("Task1:" +future1.get ()); Future Future2=Es.submit (TASK2); //wait 5 seconds before you stop the second task. Because the second task is an infinite loop.Thread.Sleep (5000); System.out.println ("Task2 Cancel:" + future2.cancel (true)); //gets the output of the third task, because performing a third task causes an exception//so the following statement will cause an exception to be thrownFuture Future3=Es.submit (TASK3); System.out.println ("TASK3:" +future3.get ()); } Catch(Exception e) {System.out.println (e.tostring ()); }       //Stop Task Execution ServiceEs.shutdownnow (); }}

Introduction of callable and 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.