|
The uncertainty of the order of execution is evident when you are executing multiple threads. So far, we have seen maximum two threads being executed parallely (Figure 12.2). Let us consider an example with three threads. Listing 12.1 has two classes. The class MessageBuddy implements Runnable and puts the functionality to print greeting based on the time of the day in its run method. The class ThreadTester creates three threads for three objects of Runnable type.
![]() |
The class ThreadTester creates three thread objects. First the object of runnable MessageBuddy class, hueyBuddy is passes as the thread target. Therefore, the run method in MessageBuddy will be executed whenever the thread messageDisplayer1 is executed. Similarly, rest two threads are created on two different MessageBuddy objects. When all three threads are started by invoking start(), the output might look something like this
Good Evening Huey!
Good Evening Huey!
Good Evening Huey!
Good Evening Huey!
Good Evening Huey!
Good Evening Dewey!
Good Evening Louie!
Good Evening Dewey!
Good Evening Louie!
Good Evening Louie!
...
As it is somewhat clear from the output, the threads are not executed one after another. In fact, their execution is intermingled in an unpredictable fashion. In a sequential execution, you might expect message Good Evening Huey! printed 100 times followed by message Good Evening Dewey! 100 times followed by message Good Evening Louie! 100 times. However, when multiple threads are running, the order in which they will execute cannot be predicted. It very much depends on the implementation of thread scheduler as well as runtime conditions in which the code is running. Thus, the output you see above is not guaranteed to be the same if you execute the exact same code again. Moreover, Java specification does not say that the threads will start running in the same order in which they were started. In other words, the order in which you invoke the start() method on each of them. Thus, you cannot say for sure that when in listing 12.1 is executed, all the messages by first thread Good Evening Huey! are printed before Good Evening Dewey!. Bear in mind there are no guarantees in what order the three threads are executed. All you can be sure of is that all three threads will keep executing until each one of them completes the execution of its run method.
|
@ |
The code example in listing 12.1 is printing the message 100 times just to prolong the time required to execute the every thread. If the run method prints just one message, it will probably be executed too quickly and you may not be able to see the effects of multithreading and thread scheduling on output. |