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


