V - 未来的
get方法返回的结果类型
public interface Future<V>
Future计算的结果。
提供方法来检查计算是否完成,等待其完成,并检索计算结果。
结果只能在计算完成后使用方法get进行检索,如有必要,阻塞,直到准备就绪。
取消由cancel方法执行。
提供其他方法来确定任务是否正常完成或被取消。
计算完成后,不能取消计算。
如果您想使用Future ,以便不可撤销,但不提供可用的结果,则可以声明Future<?>表格的类型,并返回null作为基础任务的结果。
示例使用 (请注意,以下课程都是化妆品。)
interface ArchiveSearcher { String search(String target); } class App { ExecutorService executor = ... ArchiveSearcher searcher = ... void showSearch(final String target) throws InterruptedException { Future<String> future = executor.submit(new Callable<String>() { 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 ,所以可以由Executor执行。
例如,以上建设与submit可以替换为:
FutureTask<String> future = new FutureTask<String>(new Callable<String>() { public String call() { return searcher.search(target); }}); executor.execute(future);
内存一致性影响:异步运算采取的操作happen-before操作在另一个线程中相应的Future.get() Future.get() 。
FutureTask , Executor
boolean cancel(boolean mayInterruptIfRunning)
cancel时此任务尚未启动,则此任务不应运行。
如果任务已经开始,那么mayInterruptIfRunning参数确定是否执行此任务的线程应该以试图停止任务被中断。
此方法返回后,后续调用isDone()将始终返回true 。 随后电话isCancelled()总是返回true如果此方法返回true 。
mayInterruptIfRunning - true如果执行该任务的线程应该被中断;
否则,正在进行的任务被允许完成
false如果任务无法取消,通常是因为它已经正常完成;
true否则
boolean isCancelled()
true 。
true如果此任务在完成之前被取消
boolean isDone()
true如果任务已完成。
完成可能是由于正常终止,异常或取消 - 在所有这些情况下,此方法将返回true 。
true如果这个任务完成
V get() throws InterruptedException, ExecutionException
CancellationException - 如果计算被取消
ExecutionException - 如果计算引发异常
InterruptedException - 如果当前线程在等待时中断
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
timeout - 等待的最长时间
unit - 超时参数的时间单位
CancellationException - 如果计算被取消
ExecutionException - 如果计算抛出异常
InterruptedException - 如果当前线程在等待时中断
TimeoutException - if the wait timed out
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.