栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

对Future.get()块的方法调用。这真的可取吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

对Future.get()块的方法调用。这真的可取吗?

Future
为您提供
isDone()
不阻塞的方法,如果计算完成,则返回true,否则返回false。

Future.get()
用于检索计算结果。

您有两种选择:

  • 调用
    isDone()
    ,如果结果准备就绪,可以通过调用来请求
    get()
    ,请注意没有阻塞
  • 无限期封锁
    get()
  • 指定超时时间
    get(long timeout, TimeUnit unit)

整个

Future API
过程有一种简单的方法可以从执行并行任务的线程中获取值。如上面的项目符号所述,可以根据需要同步或异步完成此操作。

用CACHE示例更新

这是 Java Concurrency In Practice中的 一个缓存实现,是一个非常好的用例

Future

  • 如果计算已经在运行,则对计算结果感兴趣的调用方将等待计算完成
  • 如果结果已在缓存中准备好,则调用者将收集它
  • 如果结果尚未准备好并且尚未开始计算,则调用方将开始计算并将结果包装在
    Future
    其他调用方中。

使用

Future
API 可以轻松实现所有目标。

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());        }    }  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号