jdk源码中很多地方死循环都是使用for(;;)这种,比如ReentrantLock的加锁阶段,为什么不使用while(true)
public class ForVsWhile {
public void stopByFor(){
for(;;){}
}
public void stopByWhile(){
while (true){}
}
}
查看上面这个代码的字节码,可以看到两种实现没有区别
Last modified 2019-10-30; size 433 bytes
MD5 checksum dbe5c472e12297979f06534ca7184b01
Compiled from "ForVsWhile.java"
public class ForVsWhile
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #3.#16 // java/lang/Object."<init>":()V
#2 = Class #17 // ForVsWhile
#3 = Class #18 // java/lang/Object
#4 = Utf8 <init>
#5 = Utf8 ()V
#6 = Utf8 Code
#7 = Utf8 LineNumberTable
#8 = Utf8 LocalVariableTable
#9 = Utf8 this
#10 = Utf8 LForVsWhile;
#11 = Utf8 stopByFor
#12 = Utf8 StackMapTable
#13 = Utf8 stopByWhile
#14 = Utf8 SourceFile
#15 = Utf8 ForVsWhile.java
#16 = NameAndType #4:#5 // "<init>":()V
#17 = Utf8 ForVsWhile
#18 = Utf8 java/lang/Object
{
public ForVsWhile();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 5: 0
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this LForVsWhile;
public void stopByFor();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=0, locals=1, args_size=1
0: goto 0
LineNumberTable:
line 7: 0
LocalVariableTable:
Start Length Slot Name Signature
0 3 0 this LForVsWhile;
StackMapTable: number_of_entries = 1
frame_type = 0 /* same */
public void stopByWhile();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=0, locals=1, args_size=1
0: goto 0
LineNumberTable:
line 11: 0
LocalVariableTable:
Start Length Slot Name Signature
0 3 0 this LForVsWhile;
StackMapTable: number_of_entries = 1
frame_type = 0 /* same */
}
SourceFile: "ForVsWhile.java"