我经常需要让一个线程等待另一个线程的结果。似乎在 java.util.concurrent 中应该对此有一些支持,但我找不到。
Exchanger与我所说的非常接近,但它是双向的。我只希望线程 A 在线程 B 上等待,而不是让两者相互等待。
是的,我知道我可以使用 CountDownLatch 或 Semaphore 或 Thread.wait() 然后自己管理计算结果,但似乎我必须在某处缺少便利类。
我错过了什么?
更新
// An Example which works using Exchanger
// but you would think there would be uni-directional solution
protected Exchanger<Integer> exchanger = new Exchanger<Integer>();
public void threadA() {
// perform some computations
int result = ...;
exchanger.exchange(result);
}
public void threadB() {
// retrieve the result of threadA
int resultOfA = exchanger.exchange(null);
}