如果我在无限循环中启动线程会发生什么

What happens if I start threads in infinite loop

请检查以下代码

public class InfiniteThreads {
    public static int cnt=0;
    public static void main(String[] args) {
        while (true) {          
            new MyThread().start();
        }
    }

}

class MyThread extends Thread{
    @Override
    public void run() {
    sleep(100000);
    System.out.println(InfiniteThreads.cnt++);
    }
}

先不说对机器性能的影响,我很好奇exception/error程序在这种情况下会抛出什么?

您的 Threads 内部没有无限循环。您正在不停地创建线程,但它们只会递增并打印一行。之后他们就死了。

正如 Murat 所解释的那样,您正在创建短线程,如果您需要 来获得 WhosebugException 只需:

class MyThread extends Thread{
    @Override
    public void run() {
        this.run();
    }
}

官方的回答应该是,"The behavior is undefined."

Java 语言规范 (JLS) 没有说明多少线程太多了,也没有说明当您的程序达到限制时会发生什么。

java.lang.Thread的 javadoc 建议可能会抛出 OutOfMemoryError。

On some platforms, specifying a higher value for the stackSize parameter may allow [...]. Similarly, specifying a lower value may allow a greater number of threads to exist concurrently without throwing an OutOfMemoryError (or other internal error).

我在 IBM JVM 中尝试创建新线程时遇到了 OutOfMemoryError,但是如果您在一些不同的 JVM 中尝试实验,您可能会得到不同的结果。