Java - multithreaded code does not run faster on more cores

后端 未结 5 1646
半阙折子戏
半阙折子戏 2021-02-10 22:59

I was just running some multithreaded code on a 4-core machine in the hopes that it would be faster than on a single-core machine. Here\'s the idea: I got a fixed number of thre

5条回答
  •  梦谈多话
    2021-02-10 23:12

    The code inside runnable does not actually do anything.
    In your specific example of 4 threads each thread will sleep for 2.5 seconds and wait for the others via the barier.
    So all that is happening is that each thread gets on the processor to increment i and then blocks for sleep leaving processor available.
    I do not see why the scheduler would alocate each thread to a separate core since all that is happening is that the threads mostly wait.
    It is fair and reasonable to expect to just to use the same core and switch among threads
    UPDATE
    Just saw that you updated post saying that some work is happening in the loop. What is happening though you do not say.

提交回复
热议问题