java中for(;;)和while(true)的区别

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"

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值