多线程 Java 应用程序能否很好地利用多核机器?
如果我编写一个多线程 java 应用程序,JVM 会负责利用所有可用的内核吗?我需要做一些工作吗?
If I write a multi-threaded java application, will the JVM take care of utilizing all available cores? Do I have to do some work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除非您使用具有所谓“绿色”线程(现在已经很少了)的 JVM,否则 Java 线程是由操作系统线程运行的,因此默认情况下多个线程会在不同的内核上运行。
Unless you use a JVM that has so-called "green" threads (which is very few these days), Java threads are run by OS threads, so multiple threads get run on different cores by default.
接下来,当我在双核上运行此代码时,我发现两个核心的使用率均为 100%。如果我将线程数量从 2 个增加到 1 个,一个核心将达到 100%,另一个核心将达到 4% 左右。
To follow up, I see 100% usage on both cores when I run this code on my dual core. If I bring the number of threads from two to one, one core goes to 100% and another about 4%.
所有现代 JVM 都会利用与您的硬件一样多的内核。说明这一点的一个简单方法是在您的计算机上下载并运行 DaCapo 基准测试。 lusearch 基准测试使用 32 个线程。如果您在台式机或服务器上运行此程序,您应该会看到测试期间所有 CPU 利用率均达到 100%。
All modern JVMs will take advantage of as many cores as your hardware has. An easy way to illustrate this is to download and run the DaCapo benchmark on your machine. The lusearch benchmark uses 32 threads. If you run this on your desktop or server, you should see all of your CPUs hit 100% utilization during the test.
另一方面,有时“绑定”/设置 Java 进程的关联性以仅使用一组核心/套接字是有用的,尽管这是通过操作系统语义完成的。正如前面所回答的,大多数运行时确实会使用所有 cpu,并且高度线程的应用程序可能会消耗比您预期更多的资源。
On the flip of that, it is sometimes useful to "bound"/set affinity for a Java process to only use a set of cores/sockets, though done via OS semantics. As previously answered, most runtimes indeed employ all cpus and with highly threaded apps can eat up more resources than you might expect.