|
There is only one JVM and multiple threads are trying to use it. They must work out some schedule for using it, so that they all can run. Java has a scheduler (in JVM) that implements the thread scheduling. When multiple threads are running, it gets to decide which thread should run at any given moment. It also has an authority to take the turn-of-execution away from the currently executing thread and award it to another.
Rough working of the thread scheduler
Specification for JVM says little about how a thread scheduler is to be implemented. Hence, you cannot be sure about the exact implementation. However, roughly it works like this. It maintains a pool of threads, which are ready-to-run. These are the threads which are created (by instantiating Thread) and whose start() method is called, but who did not get to execute yet. The thread scheduler selects one thread from this pool (based on some scheduling algorithm) and runs it. Figure 12.2 illustrates how the thread scheduler picks the thread from the thread pool.

Figure 12.2 Thread schedular picks one of the many ready-to-run threads and allows it to run
There are two broad possibilities, either the thread will complete its execution or the scheduler will move it back to the pool of threads ready to be executed. Thus, the thread object goes back and forth between ready-to-run and running states until it finishes its execution.
As Java makes use of native threads for the execution of multiple threads, the scheduler implementation differs within various implementations of JVM. The mapping of Java threads on Native threads and their scheduling is very much JVM implementation specific. But what ever is the implementation the thread’s behavior is consistent among all the implementations.