OutOfMemoryError是什么错误?

1.OutOfMemoryError是什么错误?

  • OutOfMemoryError 表示堆内存溢出
  • 也即我们启动Java程序时,通过 -Xmx 参数指定的最大堆内存都用光了

2.请编写一个Java程序使其发生OutOfMemoryError错误

  • while(true)循环体当中,不断创建新线程,最终将产生OutOfMemoryError错误,示例代码如下:
public class OutOfMemoryErrorDemo {

    public static void main(String[] args) {

        while (true) {
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.execute(() -> System.out.println("创建新线程~"));
        }
    }
}
  • 代码执行结果,见下图:
    OutOfMemoryError是什么错误?_第1张图片

你可能感兴趣的:(Java)