您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

等到未来 已经完成了

等到未来 已经完成了

据我所知,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();
    }
}

尽管只有将其插入执行代码之前它才有效,否则执行代码将不会具有newdoTask()方法。但是,如果您不能以某种方式在执行之前获得对Future对象的控制,我真的看不到没有轮询就无法执行此操作的方法

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

/**
 * Extremely ugly way of implementing WaitHandle.WaitAny for Thread.Join().
 */
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();
    }
}
其他 2022/1/1 18:29:24 有358人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶