Witscale Test Center

12.1 Thread basics > 12.1.7 What happens behind the scene when multiple threads are executed?


12.1.7 What happens behind the scene when multiple threads are executed?

When multiple threads are executing, a thread can come out of running state at any time and has to wait until it runs next time. To successfully resume what it was doing previously, a thread must remember the context in which it was working. In case of single threaded Java program, the program context in maintained in JVM stack area that stores the local variables and partial results, and plays a part in method invocation and return.  We saw earlier (chapter 5) how method call stack keeps record of which methods are called by the currently executing program.

In multithreading application, each thread runs as an individual process. Hence, each one of them also needs to maintain the context in which they were running. Therefore, they have a separate JVM stack to keep the current context. Figure 12.4 shows how two method call stacks are maintained when a program has two threads.


 

Figure 12.4 Threads execute as lightweight processes each one with individual stack

 

When main() method is invoked, main thread is created and started. This thread has its own call stack. This thread creates another thread when it invokes myThread.start(). This newly created thread has its own method call stack. Each of these stacks maintains the context for one thread and they keep modifying as the execution of that thread progresses. Therefore, even if these threads are moved out of running state, they still know what was the context (which methods were called, what variable were declared) at that point in time so that when they again get a chance to run, they can resume from where they left off.

 

@

You need not know about the method call stacks of a thread for exam. However, knowing them will help you understand why threads are called as “execution contexts” or lightweight processes and also how they manage to keep moving in and out of running state without ever loosing the correctness of execution.