为什么当我增加最大堆大小时,最大线程数会减少?
2022-09-03 06:48:18
此测试显示可以在 Java 中创建的最大线程数
System.out.println("Max memory " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
for (int i = 0;; i++) {
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
};
};
try {
t.start();
} catch (Error e) {
System.out.println("Max threads " + i);
e.printStackTrace();
System.exit(1);
}
}
当我用默认堆大小(256M)运行它时,我得到
Max memory 247M
Max threads 2247
java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:691)
at test.Test1.main(Test1.java:19)
当我将最大堆大小增加到512M时,我得到
Max memory 494M
Max threads 1906
...
当我将最大堆大小增加到1024M时,我得到
Max memory 989M
Max threads 1162
...
也就是说,堆内存越多,线程越少。为什么?