1,简介与作用
1)代表一个异步计算的结果
represents the result of an asynchronous computation.
Future<V>是一个泛型接口,V代表future执行的任务返回值类型。
image.png
2)接口中定义的方法
V get();Waits if necessary for the computation to complete, and then retrieves its result.
等待计算的完成,并取回结果。
V get(long timeout, TimeUnit unit);Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
最大等待timeout时长,然后如果可以获取的话,就取回结果,超时则抛出TimeoutException。
boolean isDone();Returns true if this task completed.
boolean isCancelled();Returns true if this task was cancelled before it completed normally.
boolean cancel(boolean mayInterruptIfRunning);Attempts to cancel execution of this task. 参数代表whether this task should be interrupted
3)Future接口常用的实现类
public interface RunnableFuture<V> extends Runnable, Future<V>接口继承了Runnable和Future接口。
public class FutureTask<V> implements RunnableFuture<V>A cancellable asynchronous computation. FutureTask can be used to wrap a Runnable object. A FutureTask can be submitted to an Executor.
4)FutureTask中有私有成员。can be used to wrap a Callable object
private Callable<V> callable;image.png
2,实现代码执行的超时。
1)
通过Java线程池ExecutorService类配合Future接口实现,处理的都是比较耗时的操作,超过一定时间没有返回结果,就结束线程。 2)异步计算增加超时时间实例
image.png
image.png
网友评论