This question already has an answer here:
- Do “nothing” while “condition” 5 answers
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));
}
Why would they use
do { } while (tryAdvance(action));
instead of
while(tryAdvance(action));
?
Are there any advantages I am not aware of?
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.
来源:https://stackoverflow.com/questions/37323549/weird-loops-used-in-spliterator-of-java-8