Future 深入理解

来源:互联网 发布:小众软件下载免费 编辑:程序博客网 时间:2024/06/05 20:52

Future 表示异步计算的结果,提供了一些方法来检查是否计算完成,等待计算完成和取回计算结果。
当运算完成后只能通过 get 方法来获取结果。 必要时会阻塞当前线程直到计算完成。
通过cancel方法可以取消任务的执行。
其它方法用来决定任务是否正常执行完成还是被取消了,任务执行完成的任务不能被取消。
如果你想要使用Future的取消任务执行的功能而不不需要取得计算结果,那么你可以声明范性为 Future<?>,然后return null 作为计算的结果。
原文

A Future represents the result of an asynchronous computation. Methods
are provided to check if the computation is complete, to wait for its
completion, and to retrieve the result of the computation. The result
can only be retrieved using method get when the computation has
completed, blocking if necessary until it is ready. Cancellation is
performed by the cancel method. Additional methods are provided to
determine if the task completed normally or was cancelled. Once a
computation has completed, the computation cannot be cancelled. If you
would like to use a Future for the sake of cancellability but not
provide a usable result, you can declare types of the form Future<?>
and return null as a result of the underlying task.

下面是使用Future的样子,注意类的构成

 interface ArchiveSearcher { String search(String target); } class App {   ExecutorService executor = ...   ArchiveSearcher searcher = ...   void showSearch(final String target)       throws InterruptedException {     Future future       = executor.submit(new Callable() {         public String call() {             return searcher.search(target);         }});     displayOtherThings(); // do other things while searching     try {       displayText(future.get()); // use future     } catch (ExecutionException ex) { cleanup(); return; }   } }}

FutureTask 是Future的实现,并且它也实现了Runnable接口,可以通过execute方法来执行。例如:上面submit的运行方式也可以用下面的方式来替代。

FutureTask<String> future =   new FutureTask(new Callable() {     public String call() {       return searcher.search(target);   }}); executor.execute(future);}

FutureTask是异步任务执行最重要的一个自带的内部实现类,下一篇研究FutureTask的实现原理。
内存一致性影响:异步的计算的任务 在 Future.get() 满足happen-before,即Future.get()先执行的话将优先获得执行结果。

表示Future.get() 返回的执行结果。

下面是方法:

boolean cancel(boolean mayInterruptIfRunning);

尝试取消任务的执行,如果任务已经执行完成,或者已经被取消了,又或者由于其它原因不能取消,那么这个尝试可能失败。
如果任务还未执行,并且cancel被调用成功,那么这个任务将不会被执行。
如果任务已经开始执行了,mayInterruptIfRunning参数来决定是在停止任务过程中是否可以中断。
调用cancel方法返回后,isDone方法调用的结果将总是返回true,如果 cancel 方法返回true,那么isCancelled也将返回true。
mayInterruptIfRunning:如果为true,表示执行中的任务可以被中断,否则,可以等待执行中的任务完成。
如果不能取消,返回false(例如它已经执行完成了),否则返回true。


boolean isCancelled();

如果在任务正常完成前,任务被取消,返回 true


boolean isDone();

如果任务执行完成,返回true, 可能由于正常中止,异常或者被cancel,这些情况下该方法返回true


V get() throws InterruptedException, ExecutionException;

返回任务执行结果,需要的话会等待任务执行完成。
返回任务执行结果


V get(long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException;    返回任务执行结果,需要的话会等待任务执行完成,等待时间不超过超市时长。

返回任务执行结果

0 0
原创粉丝点击