Future为您提供
isDone()不阻塞的方法,如果计算完成,则返回true,否则返回false。
Future.get()用于检索计算结果。
您有两种选择:
- 调用
isDone()
,如果结果准备就绪,可以通过调用来请求get()
,请注意没有阻塞 - 无限期封锁
get()
- 指定超时时间
get(long timeout, TimeUnit unit)
整个
Future API过程有一种简单的方法可以从执行并行任务的线程中获取值。如上面的项目符号所述,可以根据需要同步或异步完成此操作。
用CACHE示例更新
这是 Java Concurrency In Practice中的 一个缓存实现,是一个非常好的用例
Future。
- 如果计算已经在运行,则对计算结果感兴趣的调用方将等待计算完成
- 如果结果已在缓存中准备好,则调用者将收集它
- 如果结果尚未准备好并且尚未开始计算,则调用方将开始计算并将结果包装在
Future
其他调用方中。
使用
FutureAPI 可以轻松实现所有目标。
package net.jcip.examples;import java.util.concurrent.*;public class Memoizer <A, V> implements Computable<A, V> { private final ConcurrentMap<A, Future<V>> cache = new ConcurrentHashMap<A, Future<V>>(); private final Computable<A, V> c;public Memoizer(Computable<A, V> c) { this.c = c;}public V compute(final A arg) throws InterruptedException { while (true) { Future<V> f = cache.get(arg); // computation not started if (f == null) { Callable<V> eval = new Callable<V>() { public V call() throws InterruptedException { return c.compute(arg); } }; FutureTask<V> ft = new FutureTask<V>(eval); f = cache.putIfAbsent(arg, ft); // start computation if it's not started in the meantime if (f == null) { f = ft; ft.run(); } } // get result if ready, otherwise block and wait try { return f.get(); } catch (CancellationException e) { cache.remove(arg, f); } catch (ExecutionException e) { throw LaunderThrowable.launderThrowable(e.getCause()); } } }}


