Multithreading enables multiple tasks in a program to be executed concurrently.
One of the powerful features of Java is its built-in support for multithreading—the concurrent running of multiple tasks within a program. In many programming languages, you have to invoke system-dependent procedures and functions to implement multithreading. This chapter introduces the concepts of threads and how multithreading programs can be developed in Java.
Thread Concepts
A program may consist of many tasks that can run concurrently. A thread is the flow of execution, from beginning to end, of a task.
A thread provides the mechanism for running a task. With Java, you can launch multiple threads from a program concurrently. These threads can be executed simultaneously in multiprocessor systems, as shown in Figure
-
(a) Here multiple threads are running on multiple CPUs.
-
(b) Here multiple threads share a single CPU.
Multithreading can make your program more responsive and interactive, as well as enhance performance. For example, a good word processor lets you print or save a file while you are typing. In some cases, multithreaded programs run faster than single-threaded programs even on single-processor systems.
You can create additional threads to run concurrent tasks in the program. In Java, each task is an instance of the Runnable interface, also called a runnable object . A thread is essentially an object that facilitates the execution of a task.
Benefiting From Multithreading
Multithreading your code can help in the following areas:
-
Improving Application Responsiveness
-
Using Multiprocessors Efficiently
-
Improving Program Structure
-
Using Fewer System Resources
Question
-
Why is multithreading needed? How can multiple threads run simultaneously in a single-processor system?
-