Based on the question on Linux, this is effective way to hogging the CPU until 2.6.38. How about JVM? Assume we have implemented the lock free algorithm, all these threads are totally independent from each other. Will more threads help us to gain more CPU time from the system?
3 回答
The short answer is yes. More processes will also result in getting more CPU time.
The default assumption of a typical scheduler on a modern operating system is that anything that asks for CPU time intends to use the CPU to make useful forward progress and it's generally more important to make as much forward progress as possible than to be "fair". If you have some notion of fairness that's important to your particular workload, you can specifically configure it in most operating systems.
More threads will use more cpu time. However, you also get much more overhead and you can end up getting less useful work done. For a cpu bound process where your threads can work independently, the optimal number of threads can be number of cpus you have, rarely more. For system resource limited processes, the optimal number can be one. For external to the system limited processes, you can actually gain by having more threads than cpus but it would be a mistake to assume this is always the case.
in short, is your goal to burn cpu or is it to get something done.
Assume we have implemented the lock free algorithm, all these threads are totally independent from each other. Will more threads help us to gain more CPU time from the system?
Not exactly sure what you are asking. The JVM can certainly go above 100% and take over more than a single CPU if your threads use a lot of CPU. IO bound applications, regardless of the number of threads, might spike over 100% but never do it sustained. If you program is waiting on web connections or reading and writing to the disk, they may max out the IO chain and not run much concurrent processing.
When the JVM forks a thread (depending on the arch) it works with the OS to allocate an OS thread. In linux these are called clones and you can see them in the process table with the right args to ps. If you fork 100 threads in your JVM, there are 100 corresponding clones in the linux kernel. If all of them are spinning (i.e. not waiting on some system resource) then the OS will give them all time slices of available CPU depending on priority and competition with other applications and system processes.