|
When multiple threads are executing, you cannot say for sure, in what order the thread scheduler will schedule and execute them. The working of thread scheduler gives some idea why the order of execution of threads is so unpredictable. We know how the threads in ready-to-run state are picked by the scheduler and executed. But we do not know how the thread scheduler decides which thread to pick first. The closest answer we can get is - It depends on what scheduling algorithms the thread scheduler uses in its implementation. Even after you know the scheduling algorithms, you still cannot be sure which one has been implemented in the JVM you are using. Java makes no guarantees there.
You may not know exactly which scheduling algorithms are used by the thread scheduler, but it certainly helps to know how some common scheduling algorithms operate. Scheduling algorithms is a dear subject for operating systems as they often do lot of jobs in parallel and multithreading can provide a greater boost to overall performance. Therefore two of the popular scheduling algorithms have the operating systems background to them. They are:
Preemptive scheduling
In preemptive scheduling, the thread scheduler preemptively (forcibly) moves a running thread to the not-ready-to-run state if either a thread of higher priority has arrived in a thread pool or if the running thread has cease to execute for some reason. (For example, if it waiting for something to happen).
Time-sliced or round-robin scheduling
The time slicing works in different manner. As its name suggest, each ready-to-run thread gets the turn-to-execute for a fixed time slot. After that, it must move back to the ready-to-run state and contend with other threads for the turn. Therefore, time slicing ensures that all threads get equal opportunity for getting their job done.
|
|
Though the order in which threads are executed is unpredictable, the order of execution within thread in always sequential. It means that the statements in the run method are always executed in the same order in which they are written. |