Callable, Future and Futuretask

Source: Internet
Author: User

Runnable is a standalone task that performs work, but it does not return any values, and if it needs to get execution results, it must be done by sharing variables or using thread communication, which can be cumbersome to use. 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 is completed.

First, Runnable

Java.lang.Runnable is an interface in which only a run () method is declared:

Because the run () method returns a value of type void, no results can be returned after the task has been executed. Second, callableCallable is located under the Java.util.concurrent package, it is also an interface, in it also only a method is declared, but this method is called call (), as follows: You can see that this is a generic interface, call () The type returned by the function is the type of V passed in. So how do you use callable? In general, it is used in conjunction with Executorservice, which declares the overloaded versions of several submit methods in the Executorservice interface: The parameter type in the first Submit method is callable.

In general, we will use callable and Executorservice, the usual loading mode is the first Submit method and a third submit method, the second submit method is seldom used.

Experimental results:

Result of Taskwithresult 0

Result of Taskwithresult 1

Result of Taskwithresult 2

Result of Taskwithresult 3

Result of Taskwithresult 4

Iii. 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:

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.

Iv. Futuretask

Let's take a look at the implementation of Futuretask:  public class FutureTask<V> implements RunnableFuture<V>Futuretask class implements the Runnablefuture interface, we look at the implementation of the Runnablefuture interface: you can see Runnablefuture inherited 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:

V. Examples of applications

1. Using callable+future to get execution results

public class Test {      public static void main(String[] args) {          ExecutorService executor = Executors.newCachedThreadPool();          Task task = new Task();          Future<Integer> result = executor.submit(task);          executor.shutdown();                   try {              Thread.sleep( 1000 );          } catch (InterruptedException e1) {              e1.printStackTrace();          }                   System.out.println( "主线程在执行任务" );                   try {              System.out.println( "task运行结果" +result.get());          } catch (InterruptedException e) {              e.printStackTrace();          } catch (ExecutionException e) {              e.printStackTrace();          }                   System.out.println( "所有任务执行完毕" );      } } class Task implements Callable<Integer>{      @Override      public Integer call() throws Exception {          System.out.println( "子线程在进行计算" );          Thread.sleep( 3000 );          int sum = 0 ;          for ( int i= 0 ;i< 100 ;i++)              sum += i;          return sum;      } }Execution Result:child threads are being evaluated
The main thread is performing the task
Task Run result 4950
All Tasks completed2. Using Callable+futuretask to get execution results public class Test {      public static void main(String[] args) {          //第一种方式          ExecutorService executor = Executors.newCachedThreadPool();          Task task = new Task();          FutureTask<Integer> futureTask = new FutureTask<Integer>(task);          executor.submit(futureTask);          executor.shutdown();                   //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread          /*Task task = new Task();          FutureTask<Integer> futureTask = new FutureTask<Integer>(task);          Thread thread = new Thread(futureTask);          thread.start();*/                   try {              Thread.sleep( 1000 );          } catch (InterruptedException e1) {              e1.printStackTrace();          }                   System.out.println( "主线程在执行任务" );                   try {              System.out.println( "task运行结果" +futureTask.get());          } catch (InterruptedException e) {              e.printStackTrace();          } catch (ExecutionException e) {              e.printStackTrace();          }                   System.out.println( "所有任务执行完毕" );      } } class Task implements Callable<Integer>{      @Override      public Integer call() throws Exception {          System.out.println( "子线程在进行计算" );          Thread.sleep( 3000 );          int sum = 0 ;          for ( int i= 0 ;i< 100 ;i++)              sum += i;          return sum;      }}

Callable, Future and 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.