为什么这个小的Java程序会让MacOS重新启动?
2022-08-31 21:04:46
代码如下
Set<Thread> threads = new HashSet<>();
Runnable r = () -> {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
for (int i = 0; i < 20000; i++) {
Thread t = new Thread(r);
threads.add(t);
t.start();
if (i % 100 == 0) {
System.out.println(i);
}
Thread.sleep(2);
}
执行时,我开始看到这样的值
0
100
200
300
正如预期的那样,它一直持续到我看到:
3900
4000
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:717)
at App.main(scratch.java:24)
Java HotSpot(TM) 64-Bit Server VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated
但过了一会儿(10-20秒左右),MacOS决定重新启动。我在这里看到的重新启动的原因是什么?主线程抛出异常,但具有约4000个线程的进程休眠导致...操作系统中的什么?这是内存溢出还是与操作系统的任务计划程序有关?
MacOS version: 10.14.3 (18D109) java version "1.8.0_202" Java(TM) SE Runtime Environment (build 1.8.0_202-b08) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b08, mixed mode)