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

将异步计算包装为同步(阻塞)计算

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

将异步计算包装为同步(阻塞)计算

使用您自己的Future实现:

public class BazComputationFuture implements Future<Baz>, BazComputationSink {    private volatile Baz result = null;    private volatile boolean cancelled = false;    private final CountDownLatch countDownLatch;    public BazComputationFuture() {        countDownLatch = new CountDownLatch(1);    }    @Override    public boolean cancel(final boolean mayInterruptIfRunning) {        if (isDone()) { return false;        } else { countDownLatch.countDown(); cancelled = true; return !isDone();        }    }    @Override    public Baz get() throws InterruptedException, ExecutionException {        countDownLatch.await();        return result;    }    @Override    public Baz get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {        countDownLatch.await(timeout, unit);        return result;    }    @Override    public boolean isCancelled() {        return cancelled;    }    @Override    public boolean isDone() {        return countDownLatch.getCount() == 0;    }    public void onBazResult(final Baz result) {        this.result = result;        countDownLatch.countDown();    }}public Future<Baz> doSomething(Foo fooArg, Bar barArg) {    BazComputationFuture future = new BazComputationFuture();    doSomethingAsync(fooArg, barArg, future);    return future;}public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {    return doSomething(fooArg, barArg).get();}

该解决方案在内部创建一个CountDownLatch,一旦收到回调,该计数器将被清除。如果用户调用get,则使用CountDownLatch阻止调用线程,直到计算完成并调用onBazResult回调。CountDownLatch将确保如果回调在调用get()之前发生,则get()方法将立即返回结果。



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

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

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