Would a multithreaded Java application exploit a multi-core machine very well?

偶尔善良 提交于 2019-12-18 05:28:07

问题


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?


回答1:


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.




回答2:


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%.

package test;

import java.util.ArrayList;

public class ThreadTest
{
    public void startCPUHungryThread()
    {
        Runnable runnable = new Runnable(){
            public void run()
            {
                while(true)
                {
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();     
    }

    public static void main(String[] args)
    {
        ThreadTest thread = new ThreadTest();
        for (int i=0; i<2; i++)
        {
            thread.startCPUHungryThread();
        }
    }
}



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1649402/would-a-multithreaded-java-application-exploit-a-multi-core-machine-very-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!