你不想要锁,但屏障: m(n + 1) 必须等到 m(n) 被调用。下面的代码假设只有一个序列或方法调用(并且 m1/2/3 从不同的线程调用或在同一线程上以正确的顺序调用,否则您将永远等待闩锁)。如果它可以发生多次,则需要重新设置(或者您可以使用 Phaser 来获得灵感)。
private CountDownLatch m2latch = new CountDownLatch(1);
private CountDownLatch m3latch = new CountDownLatch(1);
public void m1() {
// handle input
m2latch.countDown();
}
public void m2() {
m2latch.await();
// handle input (m1 has been called)
m3latch.countDown();
}
public void m3() {
m3latch.await();
// do output (both m1 + m2 have been called)
}
然而,这有点奇怪的设计,因为你想按顺序做,你应该只在输出方法中完成所有工作,它会等到所有输入都输入。
private CountDownLatch inputLatch = new CountDownLatch(3);
private Object[] input = new Object[3];
public void setInput(int i, Object data) {
input[i] = data;
inputLatch.countDown(); // perhaps better check all input set
}
public Object processInput() {
inputLatch.await();
return process(input); // process in sequence
}