Callable & Future & Futuretask

Source: Internet
Author: User

There are 2 ways to create threads, one is to inherit the thread directly, and the other is to implement the Runnable interface.

One drawback to all 2 of these approaches is that you cannot get the results of the execution after the task has been completed.

If you need to get the results of execution, you have to use shared variables or the way you use thread communication to achieve the effect, which is more troublesome.

Since the beginning of Java 1.5, callable and the future have been provided, through which the task execution results can be obtained after the task has been completed.

Today we will discuss the use of the callable, future, and futuretask three classes.

1 Callable and Runnable

Let's talk about Java.lang.Runnable, it's an interface that only declares a run () method in it:

 Public Interface Runnable {    publicabstractvoid  run ();}

Because the run () method returns a value of type void, no results can be returned after the task has been executed.

Callable is located under the Java.util.concurrent package, which is also an interface, in which only one method is declared, but this method is called call ():

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:

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

The parameter type in the first Submit method is callable.

For the time being only need to know that callable is generally used with the Executorservice, the specific use of the method is explained in the following.

In general we use the first Submit method and the third submit method, and the second submit method is seldom used.

2 Future

The future is to cancel the execution result of the specific runnable or callable task, whether the query is completed, and the result is obtained. If necessary, the result of the execution can be obtained through the Get method, which blocks until the task returns the result.

The future class is located under the Java.util.concurrent package, which is an interface:

1  Public InterfaceFuture<v> {2     BooleanCancelBooleanmayinterruptifrunning);3     Booleaniscancelled ();4     BooleanIsDone ();5V get ()throwsinterruptedexception, executionexception;6V Get (LongTimeout, timeunit unit)7         throwsinterruptedexception, Executionexception, timeoutexception;8}

5 methods are declared in the future interface, which in turn explains the function of each method:

    • The Cancel method is used to cancel the task and returns true if the Cancel task succeeds, or False if the cancel task fails. The parameter mayinterruptifrunning indicates whether a task that is executing but not completed is allowed to be canceled, and if set to true, it means that the task in the process of execution can be canceled. If the task is completed, whether mayinterruptifrunning is true or FALSE, this method will definitely return false, that is, if canceling the completed task returns false, or if the task is executing, Returns True if the mayinterruptifrunning is set to true, or False if the mayinterruptifrunning is set to false, or if the task has not been executed, Returns true regardless of whether mayinterruptifrunning is true or false.
    • The IsCancelled method indicates whether the task was canceled successfully and returns true if the task was canceled successfully before it was properly completed.
    • The Isdone method indicates whether the task has completed and returns true if the task completes;
    • The Get () method is used to get the result of the execution, this method will be blocked, will wait until the task is completed before returning;
    • Get (long timeout, timeunit unit) is used to get the execution result, and if the result is not obtained within the specified time, NULL is returned directly.

This means that the future offers three functions:

1) Determine whether the task is completed;

2) ability to interrupt tasks;

3) Ability to get task execution results.

Because the future is just an interface, it is not directly used to create objects, so there is the following futuretask.

3 Futuretask

Let's take a look at the implementation of Futuretask:

   public class FutureTask<V>  implements RunnableFuture<V>

The Futuretask class implements the Runnablefuture interface, and we look at the implementation of the Runnablefuture interface:

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

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.

The Futuretask provides 2 constructors:

1  Public Futuretask (callable<v> callable) {2}3 public futuretask ( Runnable Runnable, V result) {4 }

In fact, Futuretask is a unique implementation class for the future interface.

4 Use examples

1. Using callable+future to get execution results

1  Public classTest {2      Public Static voidMain (string[] args) {3Executorservice executor =Executors.newcachedthreadpool ();4Task task =NewTask ();5future<integer> result =Executor.submit (Task);6 Executor.shutdown ();7          8         Try {9Thread.Sleep (1000);Ten}Catch(interruptedexception E1) { One e1.printstacktrace (); A         } -           -System.out.println ("Main thread is performing tasks"); the           -         Try { -SYSTEM.OUT.PRINTLN ("Task run result" +result.get ()); -}Catch(interruptedexception e) { + e.printstacktrace (); -}Catch(executionexception e) { + e.printstacktrace (); A         } at           -System.out.println ("All Tasks Completed"); -     } - } - classTaskImplementsCallable<integer>{ - @Override in      PublicInteger Call ()throwsException { -SYSTEM.OUT.PRINTLN ("Child threads are being evaluated"); toThread.Sleep (3000); +         intsum = 0; -          for(inti=0;i<100;i++) theSum + =i; *         returnsum; $     }Panax Notoginseng}

Execution Result:

The child thread performs the task in the main thread of the calculation 4950 all tasks are completed
2. Using Callable+futuretask to get execution results
1  Public classTest {2      Public Static voidMain (string[] args) {3         //The first way4Executorservice executor =Executors.newcachedthreadpool ();5Task task =NewTask ();6Futuretask<integer> Futuretask =NewFuturetask<integer>(Task);7 Executor.submit (futuretask);8 Executor.shutdown ();9          Ten         //The second way, note that this approach is similar to the first, except that one is using Executorservice, one using thread One         /*Task task = new Task (); A futuretask<integer> futuretask = new futuretask<integer> (Task); - thread thread = new Thread (futuretask); - Thread.Start ();*/ the           -         Try { -Thread.Sleep (1000); -}Catch(interruptedexception E1) { + e1.printstacktrace (); -         } +           ASystem.out.println ("Main thread is performing tasks"); at           -         Try { -SYSTEM.OUT.PRINTLN ("Task run result" +futuretask.get ()); -}Catch(interruptedexception e) { - e.printstacktrace (); -}Catch(executionexception e) { in e.printstacktrace (); -         } to           +System.out.println ("All Tasks Completed"); -     } the } * classTaskImplementsCallable<integer>{ $ @OverridePanax Notoginseng      PublicInteger Call ()throwsException { -SYSTEM.OUT.PRINTLN ("Child threads are being evaluated"); theThread.Sleep (3000); +         intsum = 0; A          for(inti=0;i<100;i++) theSum + =i; +         returnsum; -     } $}

If you use the future for the sake of cancellation and do not provide the available results, you can declare the Future<?> form type and return null as the result of the underlying task.

Reprinted from:

http://www.cnblogs.com/dolphin0520/

Callable & Future & Futuretask

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.