我正在研究一个可编写脚本的对象模型,其中包括用于异步计算的完成对象,以便最终用户脚本可以等待完成对象的逻辑组合。问题是,如果我通过wait()
and notify()
/使用内置监视器对象,notifyAll()
则没有等待多个对象的机制;如果我使用CountDownLatch
它还不清楚如何组合多个对象。
我想要这样的东西:
/** object representing the state of completion of an operation
* which is initially false, then becomes true when the operation completes */
interface Completion
{
/** returns whether the operation is complete */
public boolean isDone();
/** waits until the operation is complete */
public void await() throws InterruptedException;
}
class SomeObject
{
public Completion startLengthyOperation() { ... }
}
class Completions
{
public Completion or(Completion ...objects);
public Completion and(Completion ...objects);
}
以便脚本或最终应用程序可以执行此操作:
SomeObject obj1, obj2, obj3;
... /* assign obj1,2,3 */
Completion c1 = obj1.startLengthOperation();
Completion c2 = obj2.startLengthOperation();
Completion c3 = obj3.startLengthOperation();
Completion anyOf = Completions.or(c1,c2,c3);
Completion allOf = Completions.and(c1,c2,c3);
anyOf.await(); // wait for any of the 3 to be finished
... // do something
allOf.await(); // wait for all of the 3 to be finished
... // do something else
如果我使用 using 来实现,这个and()
案例很容易处理CountDownLatch
——我只是以任何顺序等待所有这些。但是我该如何处理这个or()
案子呢?