应用程序在JVM终止之前可以生成多少个线程

Aid*_*dom 2 java multithreading

问:

1)在多线程应用程序中,应用程序可能产生的线程数有限制.

2)如果存在这样的限制,JVM是否终止应用程序并使用什么错误代码.

编辑

3)如果应用程序产生了非常快速的成功,JVM是否会将其检测为"粗略"应用程序

提前致谢

Mat*_*der 5

没有JVM规范指定的限制.操作系统可能(可能)像往常一样限制每个进程等.每个线程也将分配一个堆栈等,因此可能需要大量内存,因此根据计算机首先要达到的限制.

请注意:太多线程通常效率低下.你的程序可能/应该以另一种方式更好地扩展.根据您的需要使用线程池(执行器服务),异步I/O,fork/join等.

也可以看看:

Java中的许多线程是否存在硬限制?

Java VM可以支持多少个线程?


Mar*_*nik 5

您应该对其进行测试以进行设置。我为我做了:

import static java.lang.Thread.currentThread;
import java.util.concurrent.CountDownLatch;

public class Test {
  static final Thread t = currentThread();
  public static void main(String[] args) throws Exception {
    int i = 0;
    try {
      while (true) {
        final CountDownLatch l = new CountDownLatch(1);
        new Thread() { public void run() { l.countDown(); park(); }}.start();
        l.await();
        i++;
      }
    } finally { System.out.println("Started " + i + " threads."); }
  }
  private static void park() {
    try { t.join(); } catch (InterruptedException e) {
      System.out.println("Unparked");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Started 2030 threads.
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:658)
    at test.Test.main(Test.java:10)
Run Code Online (Sandbox Code Playgroud)