Java threads: How many threads are appropriate to create?

  • For CPU-intensive computing, multi-threading is essentially to improve the utilization of multi-core CPUs, so for a 4-core CPU, each core has one thread, theoretically it is enough to create 4 threads, and creating more threads is just adding threads Switching costs. Therefore, for CPU-intensive computing scenarios, theoretically "the number of threads = the number of CPU cores" is the most appropriate. However, in engineering, the number of threads is generally set to "CPU core number + 1". In this way, when a thread is blocked due to occasional memory page failure or other reasons, this extra thread can be topped up, thereby ensuring CPU. utilization rate.
最佳线程数 = CPU 核数 + 1
  • For I/O-intensive computing scenarios, if the time consumption of CPU computing and I/O operations is 1:1, then 2 threads are most suitable. If the time-consuming of CPU calculation and I/O operation is 1:2, how many threads are appropriate? There are 3 threads, and the CPU switches between threads A, B, and C. For thread A, when the CPU switches back from B and C, thread A just finishes executing the I/O operation. In this way, the utilization rate of CPU and I/O device has reached 100%.
最佳线程数 = CPU 核数 * [ 1 +(I/O 耗时 / CPU 耗时)]

Guess you like

Origin blog.csdn.net/ChinaLiaoTian/article/details/128472930