Before we look at what it means to have multiple threads, let us make sure we understand single threads. By thread
, we mean
- thread of control or
- thread of execution.
From a programmer's perspective, implementing a single thread is the classic top-down approach to software design, which a traditional language such as C promotes.
So what exactly is a thread? In Java, "thread" means two different things:
- An instance of class java.lang.Thread
- A thread of execution
An instance of Thread is just an object and like any other object in Java, it has variables and methods, and lives and dies on the heap
But a thread of execution
is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack or, one call stack per thread.
Even if you do not create any new threads in your program, threads are running in the background.
method, which starts the thread process, runs in one thread, called the main thread
. If you looked at the main call stack you would see that
is the first method on the stack, the method at the bottom.
But as soon as you create a new thread
, a new stack materializes and methods called from that thread run in a call stack that is separate from the
call stack. That second new call stack is said to run concurrently with the main thread.
What mechanism allows the code to run concurrently
The JVM, which gets its turn at the CPU by whatever scheduling mechanism the underlying OS uses, operates like a mini-OS and schedules its own threads, regardless of the underlying operating system.
In some JVMs, the Java threads are actually mapped to native OS threads, but we will not discuss that here. It is not required to understand how threads behave in different JVM environments
In fact, the most important concept to understand from this module is this:
When it comes to threads, very little is guaranteed. So be very cautious about interpreting the behavior you see on one machine as "the way threads work."
You might think of a single-threaded program as a pinball game in which you have only one ball at time. It is clear when to hit the flipper buttons, and you can follow this ball as it hits targets and bumpers. A single-threaded program starts with some initialization, performs its calculations, displays any results, and then ends. We have diagrammed an approach for a model of a town hall in the figure below.
Of course, life gets more interesting when you have to deal with multiple threads. Let's look at those next.