Infinite Loops in Java – Java中的无限循环

最后修改: 2018年 5月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll explore ways to create an infinite loop in Java.

在这个快速教程中,我们将探讨如何在Java中创建一个无限循环。

Simply put, an infinite loop is an instruction sequence that loops endlessly when a terminating condition isn’t met. Creating an infinite loop might be a programming error, but may also be intentional based on the application behavior.

简单地说,无限循环是指在不满足终止条件的情况下无休止地循环的指令序列。创建一个无限循环可能是一个编程错误,但也可能是基于应用程序的行为而有意为之。

2. Using while

2.使用while

Let’s start with the while loop. Here we’ll use the boolean literal true to write the while loop condition:

让我们从while循环开始。在这里,我们将使用布尔字样true 来编写while循环条件。

public void infiniteLoopUsingWhile() {
    while (true) {
        // do something
    }
}

3. Using for

3.使用for

Now, let’s use the for loop to create an infinite loop:

现在,让我们使用for循环来创建一个无限循环。

public void infiniteLoopUsingFor() {
    for (;;) {
        // do something
    }
}

4. Using do-while

4.使用do-while

An infinite loop can also be created using the less common do-while loop in Java. Here the looping condition is evaluated after the first execution:

也可以使用Java中不太常见的do-while循环来创建一个无限循环。这里的循环条件在第一次执行后被评估。

public void infiniteLoopUsingDoWhile() {
    do {
        // do something
    } while (true);
}

5. Conclusion

5.总结

Even though in most of the cases we’ll avoid creating infinite loops but there could be some cases where we need to create one. In such scenarios, the loop will terminate when the application exits.

尽管在大多数情况下,我们会避免创建无限循环,但在某些情况下,我们可能需要创建一个无限循环。在这种情况下,该循环将在应用程序退出时终止。

The above code samples are available in the GitHub repository.

上述代码样本可在GitHub资源库中找到。