|Lesson 2|| How multithreading works |
|Objective|| Examine what multithreading is and how it works. |
A thread is a sequence of statements that is executed as part of a
program. All programs have at least one thread of execution. Multithreaded programs are programs that simultaneously execute two
or more threads. Multithreading support is provided by the underlying operating system, which quickly switches the system's
CPU (or CPUs) between running threads. The portion of the operating system that assigns threads to CPUs is the thread scheduler, or simply the scheduler.
In single-processor systems, only one thread actually executes at a given instant. Because the thread scheduler
between running threads, it creates the appearance that multiple threads are executing simultaneously.
Even though multiple threads do not execute at the same instant, we still refer to this as multithreading.
In systems consisting of multiple processors
, more than one thread may execute at a given instant.
However, the thread scheduler still switches between multiple threads.
That is because there are almost always more threads than available processors.
- Thread: A sequence of statements that is executed as part of a program.
- Multithreaded program: A program that simultaneously supports more than one thread of execution.
- Thread scheduler: The part of an operating system that assigns threads to CPUs. Also referred to as the scheduler.
- Scheduler: The part of an operating system that assigns threads to CPUs. Also referred to as the thread scheduler.
The advantage of multithreading is that it allows your programs to do more things at the same time.
For example, you can have an applet that simultaneously performs a sequence of calculations while displaying the results of the calculations in a chart.
Another advantage of multithreading is that it lets you maximize your programming resources. For example,
one thread of a program can interact with a user, while another thread is printing output, and yet another thread is communicating over the Internet.