If each core in my cpu can handle one thread at a time, how do I use 16 or more threads

I am working on some Java programs and am just getting into real multithreading. I played around with thread counts and realized that using 20 threads was faster than 8 threads, how many physical and virtual cores I have.

Why is using 20 threads faster than using 8 when each core in my CPU can only handle one thread at a time?

+3


source to share


1 answer


the original reason for multiprocessing and multithreading to be invented has nothing to do with multiple cores. there was one core at that time. However, a program consists of a combination of I / O and computation. when a single threaded program initiates an I / O operation, it blocks a (relatively) long period of time, during which time the CPU is idle. But if there is a second thread, and this thread is not blocking on I / O, such a thread can be scheduled and used by the CPU.



To summarize: multithreading helps to overlap the I / O of a stream with the computation of other threads, hence maximizes CPU usage (is there one or more)

+6


source







All Articles