[Miscellaneous] How to determine the optimal number of threads?

First take a single-core CPU as an example:
Please add image description
why use multithreading?

  • If there is only one thread , when the task is blocked, there will be an "idle period" of the CPU, and the computing resources during this period of time will be wasted in vain
  • When using multi-threading , if the CPU is blocked, it will give up the right to use it and compete with other threads, and the blocking time of the thread will not be wasted.

Of course, the number of threads is not as much as possible, because context switching is also a time-consuming operation, so we hope to find an optimal number of threads for our system, which can not only ensure full utilization of CPU resources, but also reduce context switching. the cost of


"Java Concurrency in Practice" writes:

For CPU-intensive tasks, it is recommended to set the number of threads to the number of CPU cores + 1

"Programing Concurrency on the JVM" writes:

Minimum number of threads = number of CPU cores

Guess you like

Origin blog.csdn.net/HNU_Csee_wjw/article/details/123171044