Threads may be seen as methods that execute at "the same time" as other methods. Normally, we think sequentially when writing a computer program. From this perspective, only one thing executes at a time. However, with today's multi-core processors, it is possible to literally have several things going on at the very same time while sharing the same memory. There are lots of ways that this is done in the real world, and this chapter goes over them in a way that you can apply to your own projects.
14.2 What Is a Thread?
A thread (or a thread of execution or a thread of control) is a single sequence of
executable statements within a program. For Java applications, the flow of
control begins at the first statement in main() and continues sequentially
through the program statements. For Java applets, the flow of control
begins with the first statement in init(). Loops within a program cause
a certain block of statements to be repeated. If-else structures cause certain
statements to be selected and others to be skipped. Method calls cause the
flow of execution to jump to another part of the program, from which it
returns after the method’s statements are executed. Thus, within a single
thread, you can trace the sequential flow of execution from one statement
to the next.
One way to visualize a thread is to imagine that you could make a list
of the program’s statements as they are executed by the computer’s central processing unit (CPU). Thus, for a particular execution of a program
with loops, method calls, and selection statements, you could list each
instruction that was executed, beginning at the first, and continuing until
the program stopped, as a single sequence of executed statements. That’s
a thread!
Now imagine that we break a program up into two or more independent threads. Each thread will have its own sequence of instructions. Within a single thread, the statements are executed one after the other, as usual. However, by alternately executing the statements from one thread and another, the computer can run several threads concurrently. Even though the CPU executes one instruction at a time, it can run multiple threads concurrently by rapidly alternating among them. The main advantage of concurrency is that it allows the computer to do more than one task at a time. For example, the CPU could alternate between downloading an image from the Internet and running a spreadsheet calculation. This is the same way you ate toast and cereal and drank coffee in our earlier breakfast example. From our perspective, it might look as if the computer had several CPUs working in parallel, but that’s just the illusion created by effectively scheduling threads.