代码如下
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版本:10.14.3(18D109) Java版本:“1.8.0_202” Java(TM) SE Runtime Environment(版本1.8.0_202-b08) Java HotSpot(TM) 64位服务器虚拟机(版本25.202-b08,混合模式)