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

等到未来 已经完成了

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

等到未来 已经完成了

据我所知,Java没有与该

WaitHandle.WaitAny
方法类似的结构。

在我看来,这可以通过“ WaitableFuture”装饰器来实现:

public WaitableFuture<T>    extends Future<T>{    private CountDownLatch countDownLatch;    WaitableFuture(CountDownLatch countDownLatch)    {        super();        this.countDownLatch = countDownLatch;    }    void doTask()    {        super.doTask();        this.countDownLatch.countDown();    }}

尽管只有将其插入执行代码之前它才有效,否则执行代码将不会具有new

doTask()
方法。但是,如果您不能以某种方式在执行之前获得对Future对象的控制,我真的看不到没有轮询就无法执行此操作的方法。

或者,如果将来总是在自己的线程中运行,那么您可以通过某种方式获得该线程。然后,您可以产生一个新线程来互相连接线程,然后在连接返回后处理等待机制……这确实很丑陋,但是会引起很多开销。而且,如果某些Future对象没有完成,则根据死线程,您可能会有很多阻塞线程。如果不小心,可能会泄漏内存和系统资源。

public static joinAny(Collection<Thread> threads, int numberToWaitFor){    CountDownLatch countDownLatch = new CountDownLatch(numberToWaitFor);    foreach(Thread thread in threads)    {        (new Thread(new JoinThreadHelper(thread, countDownLatch))).start();    }    countDownLatch.await();}class JoinThreadHelper    implements Runnable{    Thread thread;    CountDownLatch countDownLatch;    JoinThreadHelper(Thread thread, CountDownLatch countDownLatch)    {        this.thread = thread;        this.countDownLatch = countDownLatch;    }    void run()    {        this.thread.join();        this.countDownLatch.countDown();    }}


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

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

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