Future, FutureTask的作用和差异

来源:互联网 发布:php curl exec 编辑:程序博客网 时间:2024/05/29 09:32

 

Future是一个接口,表示一个任务的周期,并提供了相应的方法来判断是否已经完成或者取消任务,以及获取任务的结果和取消任务。

下面根据Future的定义介绍一下相关的接口


1. boolean cancel(boolean mayInterruptIfRunning);

取消任务.
fail的情况:任务已经完成,已经被取消过了,无法取消。
success的情况:任务还没有开始执行,其他由参数mayInterruptIfRunning决定。
若mayInterruptIfRunning为true,任务不可以被打断。
否则就可以允许完成。

当该方法被执行过之后,isDone()的结果输出一直为true.
如果该方法return true,isCancelled的结果输出一直为true.

return:false,如果任务不能被取消一般是因为已经被正常执行。

2.  boolean isCancelled();

检测在任务正常执行之前是否被取消。
3.   boolean isDone();

Return true is this task completed.
任务的完成包括正常的结束,exception,和取消。

4. V get() throws InterruptedException, ExecutionException;

阻塞等待任务完成,并获取计算结果。

@throws CancellationException if the computation was cancelled
@throws ExecutionException if the computation threw an exception
@throws InterruptedException if the current thread was interrupted  while waiting


5. V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

阻塞等待任务完成或者timeout的时间到了,然后获取计算结果。

@param timeout the maximum time to wait
@param unit the time unit of the timeout argument
@return the computed result
@throws CancellationException if the computation was cancelled
@throws ExecutionException if the computation threw an exception
@throws InterruptedException if the current thread was interrupted while waiting
@throws TimeoutException if the wait timed out


Future是一个接口,FutureTask是Future的一个实现类,并实现了Runnable,因此FutureTask可以传递到线程对象Thread中新建一个线程执行。所以可以通过Excutor(线程池)来执行,也可传递给Thread对象执行。

如果在主线程中需要执行比较耗时的操作,但又不想阻塞主线程时,可以把这些作业交给Future对象在后台完成,当主线程将来需要时,就可以通过Future对象获得后台作业的计算结果或者执行状态。 

FutureTask是为了弥补Thread的不足而设计的,它可以让程序员准确地知道线程什么时候执行完成并获得到线程执行完成后返回的结果(如果有需要)。
FutureTask是一种可以取消的异步的计算任务。它的计算是通过Callable实现的,它等价于可以携带结果的Runnable,并且有三个状态:等待、运行和完成。完成包括所有计算以任意的方式结束,包括正常结束、取消和异常。
Executor框架利用FutureTask来完成异步任务,并可以用来进行任何潜在的耗时的计算。一般FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。

JDK:

此类提供了对 Future 的基本实现。仅在计算完成时才能检索结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。


可使用 FutureTask 包装 Callable 或 Runnable 对象。因为 FutureTask 实现了 Runnable,所以可将 FutureTask 提交给 Executor 执行。

 

参考文章:  http://www.cnblogs.com/dolphin0520/p/3949310.html

http://uule.iteye.com/blog/1539084

 

 

 

0 0
原创粉丝点击