背景
常常看到源码中是这样的写循环的:
JDK1.8下的ThreadPoolExecutor.awaitTermination方法
当然,在JDK11_0_9下的ThreadPoolExecutor.awaitTermination方法变成了使用while
那么问题来了:
for(;;)和while(true)有区别吗?
查看字节码
测试代码
package com.hbuzzs.leetcode;
/**
* @Date 2020/11/10-15:16
*/
public class MainTest {
private void forfor() {
for (; ; ) {
}
}
private void whilewhile() {
while (true) {
}
}
public static void main(String[] args) {
MainTest mainTest = new MainTest();
}
}
for字节码:
while字节码:
可以发现两者完全一致,所以在java中两者没有区别!
当然,在C语言中有博客提到字节码是不同的,参考:https://www.imooc.com/article/43358
使用codeblocks分析for和while对应的汇编代码
for:
while:
由此可见:在新的C版本中连这个和同样是相同的,或许在早期C是不一样的吧。(参考:https://blog.csdn.net/Message_lx/article/details/81075688)