在Java 8的Spliterator中使用的奇怪循环 [英] Weird loops used in Spliterator of Java 8

查看:217
本文介绍了在Java 8的Spliterator中使用的奇怪循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么 java.util.Spliterator 实现使用do-while而不是while循环,当循环体为空时?例如, forEachRemaining 的实现是:

Does anyone know why the java.util.Spliterator implementation uses do-while rather than while loops, when the body of the loop is empty? For instance, the implementation of forEachRemaining is:

default void forEachRemaining(Consumer<? super T> action) {
    do { } while (tryAdvance(action));
}

为什么要使用

do { } while (tryAdvance(action));

而不是

while(tryAdvance(action));

我有什么优势吗?我不知道?

Are there any advantages I am not aware of?

推荐答案

逻辑检查在do {}的主体之后执行。这可以通过多种方式使用,但与最后使用逻辑检查的while循环相同。因为do {}是空的,所以线程会一直等到被通知然后执行逻辑检查,而不是执行逻辑检查,然后执行逻辑检查,如果是,则等待。

The logic check executes after the body of the do{}. This can be utilized many ways but does the same thing as a while loop with logic check at the end. Because the do{} is empty the thread will wait until notified and then execute the logic check rather than execute the logic check then if true wait.

这篇关于在Java 8的Spliterator中使用的奇怪循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆