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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/763579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:11:43  来源:igfitidea点击:

How many threads can a Java VM support?

javamultithreading

提问by McGovernTheory

How many threads can a Java VM support? Does this vary by vendor? by operating system? other factors?

Java VM 可以支持多少个线程?这是否因供应商而异?通过操作系统?其他因素?

采纳答案by Eddie

This depends on the CPU you're using, on the OS, on what other processes are doing, on what Java release you're using, and other factors. I've seen a Windows server have > 6500 Threads before bringing the machine down. Most of the threads were not doing anything, of course. Once the machine hit around 6500 Threads (in Java), the whole machine started to have problems and become unstable.

这取决于您使用的 CPU、操作系统、其他进程正在执行的操作、您使用的 Java 版本以及其他因素。在关闭机器之前,我已经看到 Windows 服务器有 > 6500 个线程。当然,大多数线程没有做任何事情。一旦机器达到 6500 个线程(在 Java 中),整个机器就开始出现问题并变得不稳定。

My experience shows that Java (recent versions) can happily consume as many Threads as the computer itself can host without problems.

我的经验表明,Java(最新版本)可以愉快地使用与计算机本身可以承载的线程一样多的线程,而不会出现问题。

Of course, you have to have enough RAM and you have to have started Java with enough memory to do everything that the Threads are doing and to have a stack for each Thread. Any machine with a modern CPU (most recent couple generations of AMD or Intel) and with 1 - 2 Gig of memory (depending on OS) can easily support a JVM with thousandsof Threads.

当然,你必须有足够的内存,并且你必须用足够的内存启动 Java 来完成线程正在做的所有事情,并且每个线程都有一个堆栈。任何具有现代 CPU(最近几代 AMD 或 Intel)和 1 - 2 Gig 内存(取决于操作系统)的机器都可以轻松支持具有数千个线程的 JVM 。

If you need a more specific answer than this, your best bet is to profile.

如果您需要比这更具体的答案,最好的办法是进行概要分析。

回答by Charlie Martin

Um, lots.

嗯,很多。

There are several parameters here. The specific VM, plus there are usually run-time parameters on the VM as well. That's somewhat driven by the operating system: what support does the underlying OS have for threads and what limitations does it put on them? If the VM actually uses OS-level threads at all, the good old red thread/green thread thing.

这里有几个参数。特定的 VM,加上 VM 上通常还有运行时参数。这在某种程度上是由操作系统驱动的:底层操作系统对线程有什么支持,它对线程有什么限制?如果虚拟机实际上完全使用操作系统级线程,那么好的旧红线程/绿线程。

What "support" means is another question. If you write a Java program that is just something like

“支持”是什么意思是另一个问题。如果您编写的 Java 程序类似于

   class DieLikeADog {
         public static void main(String[] argv){
             for(;;){
                new Thread(new SomeRunaable).start();
             }
         }
    }

(and don't complain about little syntax details, I'm on my first cup of coffee) then you should certainly expect to get hundreds or thousands of threads running. But creatinga Thread is relatively expensive, and scheduler overhead can get intense; it's unclear that you could have those threads do anything useful.

(不要抱怨小语法细节,我正在喝我的第一杯咖啡)那么您当然应该期望运行数百或数千个线程。但是创建Thread 的成本相对较高,并且调度器开销会变得很大;目前还不清楚您是否可以让这些线程做任何有用的事情。

Update

更新

Okay, couldn't resist. Here's my little test program, with a couple embellishments:

好吧,忍不住了。这是我的小测试程序,有一些装饰:

public class DieLikeADog {
    private static Object s = new Object();
    private static int count = 0;
    public static void main(String[] argv){
        for(;;){
            new Thread(new Runnable(){
                    public void run(){
                        synchronized(s){
                            count += 1;
                            System.err.println("New thread #"+count);
                        }
                        for(;;){
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e){
                                System.err.println(e);
                            }
                        }
                    }
                }).start();
        }
    }
}

On OS/X 10.5.6 on Intel, and Java 65 (see comments), here's what I got

在英特尔的 OS/X 10.5.6 和 Java 65(见评论)上,这是我得到的

New thread #2547
New thread #2548
New thread #2549
Can't create thread: 5
New thread #2550
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:592)
        at DieLikeADog.main(DieLikeADog.java:6)

回答by Ken

I recall hearing a Clojure talk where he got to run one of his apps on some specialized machine at a trade show with thousands of cores (9000?), and it loaded them all. Unfortunately, I can't find the link right now (help?).

我记得听过一次 Clojure 演讲,他在一个拥有数千个内核(9000?)的贸易展上在某台专用机器上运行他的一个应用程序,然后将它们全部加载。不幸的是,我现在找不到链接(帮助?)。

Based on that, I think it's safe to say that the hardware and your code are the limiting factors, not the JVM.

基于此,我认为可以肯定地说硬件和您的代码是限制因素,而不是 JVM。

回答by benjismith

After reading Charlie Martin's post, I was curious about whether the heap size makes any difference in the number of threads you can create, and I was totally dumbfounded by the result.

在阅读了 Charlie Martin 的帖子后,我很好奇堆大小是否会对您可以创建的线程数量产生任何影响,结果我完全傻眼了。

Using JDK 1.6.0_11 on Vista Home Premium SP1, I executed Charlie's test application with different heap sizes, between 2 MB and 1024 MB.

在 Vista Home Premium SP1 上使用 JDK 1.6.0_11,我使用不同的堆大小(2 MB 到 1024 MB)执行 Charlie 的测试应用程序。

For example, to create a 2 MB heap, I'd invoke the JVM with the arguments -Xms2m -Xmx2m.

例如,要创建一个 2 MB 的堆,我将使用参数 -Xms2m -Xmx2m 调用 JVM。

Here are my results:

这是我的结果:

2 mb --> 5744 threads
4 mb --> 5743 threads
8 mb --> 5735 threads
12 mb --> 5724 threads
16 mb --> 5712 threads
24 mb --> 5687 threads
32 mb --> 5662 threads
48 mb --> 5610 threads
64 mb --> 5561 threads
96 mb --> 5457 threads
128 mb --> 5357 threads
192 mb --> 5190 threads
256 mb --> 5014 threads
384 mb --> 4606 threads
512 mb --> 4202 threads
768 mb --> 3388 threads
1024 mb --> 2583 threads

So, yeah, the heap size definitely matters. But the relationship between heap size and maximum thread count is INVERSELY proportional.

所以,是的,堆大小肯定很重要。但是堆大小和最大线程数之间的关系是成反比的。

Which is weird.

这很奇怪。

回答by Steve K

After playing around with Charlie's DieLikeACode class, it looks like the Java thread stack size is a huge part of how many threads you can create.

在玩弄 Charlie 的 DieLikeACode 类之后,看起来 Java 线程堆栈大小是您可以创建的线程数量的重要组成部分。

-Xss set java thread stack size

-Xss 设置java线程栈大小

For example

例如

java -Xss100k DieLikeADog

java -Xss100k DieLikeADog

But, Java has the Executorinterface. I would use that, you will be able to submit thousands of Runnable tasks, and have the Executor process those tasks with a fixed number of threads.

但是,Java 有Executor接口。我会使用它,您将能够提交数千个 Runnable 任务,并让 Executor 使用固定数量的线程处理这些任务。

回答by Neil Coffey

The absolute theoretical maximumis generally a process's user address space divided by the thread stack size(though in reality, if all your memory is reserved for thread stacks, you won't have a working program...).

绝对理论上的最大值通常是一个进程的用户地址空间由线程堆栈大小分(虽然在现实中,如果你所有的记忆被保留用于线程堆栈,你会不会有一个工作程序......)。

So under 32-bit Windows, for example, where each process has a user address space of 2GB, giving each thread a 128K stack size, you'd expect an absolute maximum of 16384 threads (=2*1024*1024 / 128). In practice, I find I can start up about 13,000 under XP.

因此,例如,在 32 位 Windows 下,每个进程的用户地址空间为 2GB,为每个线程提供 128K 的堆栈大小,您预计绝对最大为 16384 个线程(=2*1024*1024 / 128)。在实践中,我发现我可以在 XP 下启动大约 13,000。

Then, I think you're essentially into whether (a) youcan manage juggling that many threads in your code and not do obviously silly things (such as making them all wait on the same object then calling notifyAll()...), and (b) whether the operating system can. In principle, the answer to (b) is "yes" if the answer to (a) is also "yes".

然后,我认为您本质上是在考虑 (a)您是否可以管理代码中的那么多线程,而不是做明显愚蠢的事情(例如让它们都等待同一个对象然后调用 notifyAll()...), (b) 操作系统是否可以。原则上,如果(a)的答案也是“是”,则(b)的答案是“是”。

Incidentally, you can specify the stack size in the constructor of the Thread; you don't need to (and probably shouldn't) mess about with VM parameters for this.

顺便说一句,您可以在 Thread 的构造函数中指定堆栈大小;您不需要(并且可能不应该)为此弄乱 VM 参数。

回答by Anil Pal

You can process any number of threads; there is no limit. I ran the following code while watching a movie and using NetBeans, and it worked properly/without halting the machine. I think you can keep even more threads than this program does.

您可以处理任意数量的线程;没有限制。我在看电影和使用 NetBeans 时运行了以下代码,它运行正常/没有停止机器。我认为你可以保留比这个程序更多的线程。

class A extends Thread {
    public void run() {
        System.out.println("**************started***************");
        for(double i = 0.0; i < 500000000000000000.0; i++) {
            System.gc();
            System.out.println(Thread.currentThread().getName());
        }
        System.out.println("************************finished********************************");
    }
}

public class Manager {
    public static void main(String[] args) {
        for(double j = 0.0; j < 50000000000.0; j++) {
            A a = new A();
            a.start();
        }
    }
}

回答by Jifeng Zhang

At least on Mac OS X 10.6 32bit, there is a limit (2560) by the operating system. Check this stackoverflow thread.

至少在 Mac OS X 10.6 32 位上,操作系统有一个限制 (2560)。检查此stackoverflow 线程

回答by Shekhar

I know this question is pretty old but just want to share my findings.

我知道这个问题已经很老了,但只是想分享我的发现。

My laptop is able to handle program which spawns 25,000threads and all those threads write some data in MySql database at regular interval of 2 seconds.

我的笔记本电脑能够处理产生25,000线程的程序,所有这些线程都以 2 秒的固定间隔在 MySql 数据库中写入一些数据。

I ran this program with 10,000 threadsfor 30 minutes continuouslythen also my system was stable and I was able to do other normal operations like browsing, opening, closing other programs, etc.

我跑这个程序与10,000 threads用于30 minutes continuously随后还我的系统是稳定的,我是能够做到像浏览,开放等正常操作,关闭其他程序,等等。

With 25,000 threadssystem slows downbut it remains responsive.

使用25,000 threads系统,slows down但它仍然响应。

With 50,000 threadssystem stopped respondinginstantly and I had to restart my system manually.

立即使用50,000 threads系统stopped responding,我不得不手动重新启动系统。

My system details are as follows :

我的系统详细信息如下:

Processor : Intel core 2 duo 2.13 GHz
RAM : 4GB
OS : Windows 7 Home Premium
JDK Version : 1.6

Before running I set jvm argument -Xmx2048m.

在运行之前,我设置了 jvm 参数-Xmx2048m

Hope it helps.

希望能帮助到你。

回答by pgp

Maximum number of threads depends on following things:

最大线程数取决于以下事项:

  • Hardware Configuration like microprocessor, RAM.
  • 硬件配置,如微处理器、RAM。
  • Operating System like whether it is 32-bit or 64-bit
  • 操作系统是 32 位还是 64 位
  • Code inside the run method. If code inside the run method is huge then single thread object will have more memory requirement
  • run 方法中的代码。如果 run 方法中的代码很大,那么单线程对象将有更多的内存需求