Callable, Future, and FutureTask, callablefuturetask

Source: Internet
Author: User

Callable, Future, and FutureTask, callablefuturetask

Two ways to create a Thread: one is to inherit the Thread directly, and the other is to implement the Runnable interface. Either of the two methods has a defect: The execution result cannot be obtained after the task is executed.

To obtain the execution result, you must share the variable or use thread communication to achieve the effect. Since Java 1.5, Callable and Future are provided, through which the task execution result can be obtained after the task is executed.

  • Callable and runnable

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

1 public interface Runnable {2     public abstract void run();3 }

Because the return value of the run () method is of the void type, no results can be returned after the task is executed.

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

1 public interface Callable<V> {2     V call() throws Exception;3 }

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

Callable is generally used in combination with ExecutorService. In the ExecutorService interface, the overloaded versions of several submit methods are declared:

1 <T> Future<T> submit(Callable<T> task);2 <T> Future<T> submit(Runnable task, T result);3 Future<?> submit(Runnable task);

In short,CallableThe interface is similarRunnableBoth are designed for classes whose instances may be executed by another thread. HoweverRunnableNo results are returned, and a checked exception cannot be thrown.

  • Future

  FutureThe result of asynchronous calculation. It provides a method to check whether the computation is complete, waiting for the computation to complete and obtaining the computation results. OnlyGetMethod to obtain results. If necessary, this method can be blocked before computation is complete. CancelCancelMethod. Other methods are provided to determine whether the task is completed normally or canceled. Once the computation is completed, the computation cannot be canceled. If you useFutureBut does not provide available results, you can declareFuture <?>Form type, and returnNullAs the result of the underlying task.

The Future class is located under the java. util. concurrent package, which is an interface:

1 public interface Future<V> {2     boolean cancel(boolean mayInterruptIfRunning);3     boolean isCancelled();4     boolean isDone();5     V get() throws InterruptedException, ExecutionException;6     V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;7 }

Five methods are defined in the Future interface. The following explains the role of each method in sequence:

  • The cancel method is used to cancel a task. if the task is canceled successfully, true is returned. If the task fails to be canceled, false is returned. The mayInterruptIfRunning parameter indicates whether to cancel a task in progress but not completed. If it is set to true, the task in progress can be canceled. If the task has been completed, no matter whether mayInterruptIfRunning is true or false, false is returned for this method, that is, false is returned if the task has been canceled; if the task is being executed, if mayInterruptIfRunning is set to true, true is returned. If mayInterruptIfRunning is set to false, false is returned. If the task has not been executed, true is returned regardless of whether mayInterruptIfRunning is true or false.
  • The isCancelled method indicates whether the task is successfully canceled. if the task is successfully canceled before it is completed, true is returned.
  • The isDone method indicates whether the task has been completed. if the task is completed, true is returned;
  • The get () method is used to obtain the execution result. This method is blocked and will not be returned until the task is executed;
  • Get (long timeout, TimeUnit unit) is used to obtain the execution result. If no result is obtained within the specified time, null is returned directly.

That is to say, Future provides three functions:

1) Determine whether the task is completed;

2) the task can be interrupted;

3) obtain the task execution result.

  • FutureTask

FutureTask implementation

1 public class FutureTask<V> implements RunnableFuture<V>

Implementation of the RunnableFuture interface:

1 public interface RunnableFuture<V> extends Runnable, Future<V> {2     void run();3 }

It can be seen that RunnableFuture inherits the Runnable and Future interfaces, while FutureTask implements the RunnableFuture interface. Therefore, it can be executed by the thread as Runnable and the return value of Callable as the Future.

Cancelable asynchronous computing. This class providesFuture. Results can be obtained only when the computation is complete. If the computation is not complete, the computation is blocked.GetMethod. Once the calculation is complete, you cannot start or cancel the calculation again.

AvailableFutureTaskPackagingCallableOrRunnableObject. BecauseFutureTaskImplementedRunnable, So you canFutureTaskSubmitExecutorRun.

  • Instance

Use future to obtain output results:

1 ExecutorService threadPool = Executors. newSingleThreadExecutor (); 2 3 Future <String> future = threadPool. submit (new Callable <String> () {4 @ Override 5 public String call () throws Exception {6 Thread. sleep (2000); 7 return "hello"; 8} 9}); 10 System. out. println ("Prepare calculation result"); 11 12 try {13 System. out. println ("Get Result:" + future. get (); 14} catch (InterruptedException e) {15 e. printStackTrace (); 16} catch (ExecutionException e) {17 e. printStackTrace (); 18}

Use CompletionService to submit a set of callable tasks, and use take () to obtain the future object corresponding to the completed callable task.

 1 ExecutorService threadPool = Executors.newFixedThreadPool(10); 2          3         CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPool); 4          5         for (int i = 0; i < 10; i++) { 6             final int seq = i; 7             completionService.submit(new Callable<Integer>() { 8                 @Override 9                 public Integer call() throws Exception {10                     Thread.sleep(new Random().nextInt(5000));11                     return seq;12                 }13             });14         }15         for (int i = 0; i < 10; i++) {16             try {17                 System.out.println(completionService.take().get());18             } catch (InterruptedException e) {19                 // TODO Auto-generated catch block20                 e.printStackTrace();21             } catch (ExecutionException e) {22                 // TODO Auto-generated catch block23                 e.printStackTrace();24             }25         }

Use Callable + Future to obtain execution results

1 public class Test {2 public static void main (String [] args) {3 ExecutorService executor = Executors. newCachedThreadPool (); 4 Task task = new Task (); 5 Future <Integer> result = executor. submit (task); 6 executor. shutdown (); 7 8 try {9 Thread. sleep (1000); 10} catch (InterruptedException e1) {11 e1.printStackTrace (); 12} 13 14 System. out. println ("the main thread is executing the task"); 15 16 try {17 System. out. println ("task running result" + result. get (); 18} catch (InterruptedException e) {19 e. printStackTrace (); 20} catch (ExecutionException e) {21 e. printStackTrace (); 22} 23 24 System. out. println ("all tasks completed"); 25} 26} 27 class Task implements Callable <Integer> {28 @ Override29 public Integer call () throws Exception {30 System. out. println ("subthread computing"); 31 Thread. sleep (3000); 32 int sum = 0; 33 for (int I = 0; I <100; I ++) 34 sum + = I; 35 return sum; 36} 37}

Use Callable + FutureTask to obtain execution results

Public class Test {public static void main (String [] args) {// The first method: ExecutorService executor = Executors. newCachedThreadPool (); Task task Task = new task (); FutureTask <Integer> futureTask = new FutureTask <Integer> (Task); executor. submit (futureTask); executor. shutdown (); // The second method. Note that the effect of this method is similar to that of the first method, except that ExecutorService is used, 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 ("the main thread is executing the task"); try {System. out. println ("task running result" + futureTask. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();} System. out. println ("all tasks completed");} class Task implements Callable <Integer >{@ Override public Integer call () throws Exception {System. out. println ("subthread computing"); Thread. sleep (3000); int sum = 0; for (int I = 0; I <100; I ++) sum + = I; return sum ;}}

Reference blog: http://www.cnblogs.com/dolphin0520/p/3949310.html

API

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.