本文目录导读:

- 最经典的 while 死循环
- for 循环中的死循环
- 浮点数精度导致的死循环(隐蔽)
- 整数溢出导致的死循环(非常隐蔽)
- 迭代器未调用next()导致的死循环
- 递归中的死循环
- 多线程死循环
- 📌 如何避免死循环?
- 💡 调试死循环的方法
我为你整理了Java中常见的死循环案例,从最简单到最隐蔽的都有:
最经典的 while 死循环
public class Demo1 {
public static void main(String[] args) {
// 条件永远为true
while (true) {
System.out.println("这是一个死循环");
}
}
}
for 循环中的死循环
public class Demo2 {
public static void main(String[] args) {
// 缺少终止条件
for (int i = 0; ; i++) {
System.out.println("i = " + i);
}
}
}
public class Demo2b {
public static void main(String[] args) {
// 条件永远不会满足
for (int i = 0; i > -1; i++) {
System.out.println("i 一直在增大");
}
}
}
浮点数精度导致的死循环(隐蔽)
public class Demo3 {
public static void main(String[] args) {
// 浮点数精度问题
double x = 0.0;
while (x != 1.0) {
x += 0.1; // 0.1 无法精确表示,永远不等于1.0
System.out.println("x = " + x);
}
}
}
整数溢出导致的死循环(非常隐蔽)
public class Demo4 {
public static void main(String[] args) {
int i = 1;
int count = 0;
while (i > 0) {
i = i * 2; // 最终溢出变成负数,但这里用的是乘法
public class Demo4b {
public static void main(String[] args) {
// 整数溢出后回到负数
for (int i = 10; i > 0; i++) {
System.out.println("i = " + i);
// 当 i 溢出到 Integer.MIN_VALUE 后,会继续增加直到溢出回来
}
}
}
迭代器未调用next()导致的死循环
import java.util.*;
public class Demo5 {
public static void main(String[] args) {
List<String> list = Arrays.asList("Java", "Python", "C++");
Iterator<String> it = list.iterator();
// 忘记调用it.next(),导致hasNext()永远为true
while (it.hasNext()) {
System.out.println("死循环,没有调用next()");
}
}
}
递归中的死循环
public class Demo6 {
public static void main(String[] args) {
// 没有终止条件的递归
recursiveMethod(1);
}
static void recursiveMethod(int n) {
System.out.println("n = " + n);
// 缺少if (n <= 0) return; 终止条件
recursiveMethod(n - 1); // 栈溢出错误
}
}
多线程死循环
public class Demo7 {
// 没有volatile修饰,可能导致死循环
private static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (flag) {
System.out.println("程序运行中...");
}
System.out.println("线程结束");
}).start();
Thread.sleep(100);
System.out.println("主线程尝试停止子线程");
flag = false; // 可能无法被子线程及时看到,导致死循环
}
}
📌 如何避免死循环?
- 确保循环条件最终会变为false
- 使用循环计数器限制最大循环次数
- 避免使用浮点数作为循环条件
- 注意整数溢出问题
- 多线程共享变量使用
volatile关键字 - 使用
break语句作为安全出口
💡 调试死循环的方法
public class DebugExample {
public static void main(String[] args) {
int count = 0;
while (true) {
count++;
// 添加保护措施,最多循环100次
if (count > 100) {
System.out.println("疑似死循环,强制退出");
break;
}
System.out.println("执行第 " + count + " 次");
}
}
}
遇到死循环时,可以使用 Ctrl+C 终止程序,或者使用IDE的 强制停止 按钮,然后通过调试器定位问题。