Java-17.6 Callable, ure, and FutureTask
In this chapter, we will discuss the usage and relationship of Callable, Future, and FutureTask.
1. Relationship
(1) Callable is an asynchronous computing task encapsulated by Runnable.
(2) Future is used to save Callable asynchronous calculation results
(3) FutureTask encapsulates the Future entity class
2. Future
Here we will introduce Future in detail, because it is complicated. First, let's look at its source code:
public interface Future
{ boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
It contains several methods
Get: The result is displayed.
Get (timeout, unit) calculation timeout result
Cancle: cancels a task.
IsDone and isCancle: Determine the task status
3. Example:
Callable and FutureTask
package com.ray.ch17;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class Test {public static void main(String[] args) throws InterruptedException,ExecutionException {Callable
callable = new MyCall();FutureTask
futureTask = new FutureTask
(callable);Thread thread = new Thread(futureTask);thread.start();Thread.sleep(100);if (!futureTask.isDone()) {System.out.println(futureTask.get());}if (!futureTask.isCancelled()) {futureTask.cancel(true);System.out.println("cancelled");}}}class MyCall implements Callable
{@Overridepublic Integer call() throws Exception {System.out.println("doing something...");Thread.sleep(1000);return new Random().nextInt(50);}}
We only need to swap the two if values in the above main method to get different results.
Callable and Future
package com.ray.ch17;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Test {public static void main(String[] args) throws InterruptedException,ExecutionException {ExecutorService executors = Executors.newCachedThreadPool();Callable
callable = new MyCall();Future
future = executors.submit(callable);System.out.println(future.get());}}class MyCall implements Callable
{@Overridepublic Integer call() throws Exception {System.out.println("doing something...");Thread.sleep(1000);return new Random().nextInt(50);}}
Summary: This chapter describes the usage and relationships of Callable, Future, and FutureTask.