经过
Java源代码的挖掘,我觉得我找到了答案.
其他线程会定期检查另一个线程是否找到答案,如果是,则它们停止工作并取消任何尚未运行的节点.
java.util.Stream.FindOps $FindTask有这个方法:
private void foundResult(O answer) {
if (isLeftmostNode())
shortCircuit(answer);
else
cancelLaterNodes();
}
它的父类AbstractShortcircuitTask这样实现shortCircuit:
/**
* Declares that a globally valid result has been found. If another task has
* not already found the answer,the result is installed in
* {@code sharedResult}. The {@code compute()} method will check
* {@code sharedResult} before proceeding with computation,so this causes
* the computation to terminate early.
*
* @param result the result found
*/
protected void shortCircuit(R result) {
if (result != null)
sharedResult.compareAndSet(null,result);
}
而实际执行的compute()方法有这个重要的一行:
AtomicReference sr = sharedResult;
R result;
while ((result = sr.get()) == null) {
...//does the actual fork stuff here
}
其中sharedResult由shortCircuit()方法更新,所以计算将在下次检查while循环条件时看到它.
编辑
所以总结一下:
>线程不会中断相反,他们会定期检查是否有人找到答案,如果已经找到答案,将会停止进一步处理.>一旦找到答案,就不会启动新的主题.