Java End tasks: Callable and future

Source: Internet
Author: User
Tags set time

Here we first introduce the next callable and future, we know 2 ways to create threads, one is to inherit the thread directly, and the other is to implement the Runnable interface, but the threads created in both ways do not return results. While callable is a similar interface definition to runnable, threads created by implementing the callable interface can have return values that can be arbitrarily defined by the return value type.

Callable interface
1  Public InterfaceCallable<v> {2     /**3 * Computes a result, or throws an exception if unable to does so.4      *5      * @returncomputed result6      * @throwsException If unable to compute a result7      */8V Call ()throwsException;9}

As you can see, this is a generic interface, and the type that the call () function returns is the type of V passed in.

So how do you use callable? Typically used in conjunction with Executorservice, the overloaded versions of several submit methods are declared in the Executorservice interface:

<T> future<t> Submit (callable<t> Task); <T> future<t> Submit (Runnable task, T result); Future <?> Submit (Runnable Task);

The parameter type in the first Submit method is callable. Callable is generally used in conjunction with the Executorservice, through the Executorservice instance submit to get the future object.

Future

The future interface is as follows:

1  Public InterfaceFuture<v> {2     BooleanCancelBooleanmayinterruptifrunning);//attempt to cancel execution of this task3     BooleanIsCancelled ();//returns True if the task is canceled before it is properly completed4     BooleanIsDone ();//returns True if the task has completed (either normal or abnormal)5V get ()throwsInterruptedexception, executionexception;//method is used to get the result of the execution, this method will be blocked and will wait until the task is completed before returning;6     //used to get the result of execution, if the result is not obtained within the specified time, return null directly;7V Get (LongTimeout, timeunit unit)throwsinterruptedexception, Executionexception, timeoutexception;8}

The future is used to represent the result of an asynchronous calculation. Its implementation class is Futuretask.

If you do not want to branch the main thread block, and want to get the results of the sub-route execution, use Futuretask

The Futuretask implements the Runnablefuture interface, which is defined as follows:

1  Public Interface extends Runnable, future<v>2{3     void  run (); 4 }

It can be seen that runnablefuture inherits the Runnable interface and the future interface, and Futuretask implements the Runnablefuture interface. So it can be executed as runnable by thread, and can get callable return value as future.

Using the example
1  Packagedemo.future;2  3 Importjava.util.ArrayList;4 Importjava.util.List;5 Importjava.util.concurrent.*;6  7 /**8 * Experiment with Java's future usage9  */Ten  Public classFuturetest { One   A      Public Static classTaskImplementsCallable<string> { - @Override -          PublicString Call ()throwsException { theString tid =string.valueof (Thread.CurrentThread (). GetId ()); -System.out.printf ("Thread#%s:in call\n", TID); -             returnTid; -         } +     } -   +      Public Static voidMain (string[] args)throwsinterruptedexception, executionexception { Alist<future<string>> results =NewArraylist<future<string>>(); atExecutorservice es =Executors.newcachedthreadpool (); -          for(inti=0; i<100;i++) -Results.add (Es.submit (NewTask ())); -   -          for(future<string>res:results) - System.out.println (Res.get ()); in     } -   to}
End Task

Holding a future object, you can call Cancel (), and therefore you can use it to interrupt a particular task, and if you pass Ture to cancel (), it will have a call to interrupt () on that thread to stop the thread's permissions. Therefore, cancel () is a way to break a single thread that is started by executor.

Cancel () is typically used with the Get () method. For example, there is a design pattern is to set a specific time, and then go to execute a job of the thread, if the job can be completed within a set time, then directly return the results, if not completed, then interrupt the execution of the job, continue to execute the next job, in this mode, Using callable and future to achieve is a very good solution.

Java End tasks: Callable and 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.