Java Multithreading, Concurrency, and Parallelism — Part 4
Multiple Threads and their Stacks
In part-3 we have seen how threads can be created and we also explored the life cycle of a thread to some extent. In this article, we will look at how threads maintain their local variables and call stacks.
Each thread in Java has a private stack associated with it. When a thread is created in Java Virtual Machine, a JVM stack local to that thread is also created.
Below is a simple java application that has one user-defined thread named MyThread
along with the main
thread.
As you can see in the above program there are two threads: main
and MyThread
.
Three things are happening in main
thread.
- The
main()
is invoked from themain
thread.main()
andmain
are different.main()
— A regular java method.main
: without parenthesis, a java thread). main()
in turn callsmethodOne()
main()
creates and stars a user-defined thread namedMyThread
.
Now MyThread
simply calls methodTwo.
Here is how the stacks look like for each of these two threads.