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

后端 未结 4 1825
慢半拍i
慢半拍i 2020-12-18 14:11

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?

4条回答
  •  隐瞒了意图╮
    2020-12-18 14:46

    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();
            }
        }
    }
    

提交回复
热议问题