Java:无限循环公约 [英] Java: Infinite Loop Convention

查看:119
本文介绍了Java:无限循环公约的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中无限循环的约定是什么?我应该写而(true) for(;;)?我个人会使用 while(true)因为我经常使用while循环。

What is the convention for an infinite loop in Java? Should I write while(true) or for(;;)? I personally would use while(true) because I use while loops less often.

推荐答案

之间的字节码没有区别,而(;;)与<$; code>之间没有区别,但我更喜欢 while(true),因为它不那么令人困惑(特别是对于刚接触Java的人)。

There is no difference in bytecode between while(true) and for(;;) but I prefer while(true) since it is less confusing (especially for someone new to Java).

您可以使用此代码示例进行检查

You can check it with this code example

void test1(){
    for (;;){
        System.out.println("hello");
    }
}
void test2(){
    while(true){
        System.out.println("world");
    }
}

当您使用命令 javap时-c ClassWithThoseMethods 你会得到

  void test1();
    Code:
       0: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #21                 // String hello
       5: invokevirtual #23                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0

  void test2();
    Code:
       0: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #31                 // String world
       5: invokevirtual #23                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0

显示相同的结构(hellovsworld字符串除外)。

which shows same structure (except "hello" vs "world" strings) .

这篇关于Java:无限循环公约的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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