java8 anymatch_java-8 – Java 8并行流anyMatch – 一旦找到匹配,线程会中断?

经过

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循环条件时看到它.

编辑

所以总结一下:

>线程不会中断相反,他们会定期检查是否有人找到答案,如果已经找到答案,将会停止进一步处理.>一旦找到答案,就不会启动新的主题.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值