Java 仅使用 2 个 CPU 内核
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20378238/
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
Use only 2 CPU cores with Java
提问by Peter Penzov
Is there a way to code Java application to use only 2 CPU cores of the CPU. For example I want to set a limit of the CPU utilization. Is this possible in Java?
有没有办法编写 Java 应用程序以仅使用 CPU 的 2 个 CPU 内核。例如,我想设置 CPU 利用率的限制。这在Java中可能吗?
回答by Jens Schauder
You can't control this directly. But if you limit the number of threads used to two it will always use only up to two cores.
你不能直接控制它。但是,如果您将使用的线程数限制为两个,则它始终最多只能使用两个内核。
But note that
但请注意
a) the actual cores used might vary since the scheduler might move threads from one core to the other
a) 实际使用的内核可能会有所不同,因为调度程序可能会将线程从一个内核移动到另一个内核
b) there might be other threads started by the JVM (e.g. for garbage collection), that you might not expect from just looking at your application.
b) JVM 可能启动了其他线程(例如,用于垃圾收集),您可能不希望仅查看您的应用程序。
回答by Damian Leszczyński - Vash
You can not assign Threads to cores, therefore you can not do that.
您不能将线程分配给内核,因此您不能这样做。
What you can do is to use JNI for such task or use the priority mechanism for Threads.
您可以做的是将 JNI 用于此类任务或使用线程的优先级机制。
回答by jarz
I believe that's something that needs to be handled at the OS level, thus can't be controlled through java code. Take a look at this post. I hope it helps.
我相信这是需要在操作系统级别处理的事情,因此无法通过 java 代码进行控制。看看这个帖子。我希望它有帮助。
Is it possible to force an existing Java application to use no more than x cores?
回答by Raffaele
If you use a pool of threads and limit the number of threads to 2, no more than 2 cores can be used at the same time. However this is a poor way of limiting CPU usage, and may not even be possible in your scenario (it depends on how many concurrent tasks your application must run).
如果使用线程池并将线程数限制为 2,则不能同时使用超过 2 个内核。然而,这是一种限制 CPU 使用率的糟糕方法,在您的场景中甚至可能无法实现(这取决于您的应用程序必须运行多少并发任务)。