Why Use Multiple Threads?

In many situations, having more than one thread running in a program is beneficial. Here’s a more in-depth look at why this can be good.

Better Interaction with the User

If only one thread was available, a program would be able to do only one thing at a time. In the word processor example, how nice it was to be able to open a second document while the first document was being formatted and queued to the printer. In some older word processors, when the user printed a document, he or she had to wait while the document was prepared for printing and sent to the printer. More modern word processors exploit multiple threads to do these two things at the same time. In a one-processor system, this is actually simulated by the operating system rapidly switching back and forth between two tasks, allowing for better user interaction.

From the perspective of a microprocessor, even the fastest typist takes a tremendous amount of time between keystrokes. In these large gaps of time, the processor can be utilized for other tasks. If one thread is always waiting to give a quick response to a user’s actions, such as clicking the mouse or pressing a key, while other threads are off doing other work, the user will perceive better response from the system.

Simulation of Simultaneous Activities

Threads in Java appear to run concurrently, even when only one physical processor exists. The processor runs each thread for a short time and switches among the threads to simulate sim-ultaneous execution. This makes it seem as if each thread has its own processor, creating a virtual multiple processor system. By exploiting this feature, you can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is running for only a brief time before the context is switched to the next thread.

Exploitation of Multiple Processors

In some machines, several real microprocessors are present. If the underlying operating system and the implementation of the JavaVM exploit the use of more than one processor, multithreaded Java programs can achieve true simultaneous thread execution. A Java program would not have to be modified because it already uses threads as if they were running on different processors simultaneously. It would just be able to run even faster.

Do Other Things While Waiting for Slow I/O Operations

Input and Output (I/O) operations to and from a hard disk or especially across a network are relatively slow when compared to the speed of code execution in the processor. As a result, read/write operations may block for quite a while, waiting to complete.

In the java.io package, the class InputStream has a method, read(), that blocks until a byte is read from the stream or until an IOException is thrown. The thread that executes this method cannot do anything else while awaiting the arrival of another byte on the stream. If multiple threads have been created, the other threads can perform other activities while the one thread is blocked, waiting for input.

Figure 1.2 shows an abstract pseudo-code model of how two threads can be Threads used to provide better user interaction. The first thread is the GUI event thread, and it spends most of its time blocked in the waitForNextEvent() method. The second thread is the worker thread, and it is initially blocked, waiting for a signal to go to work in the waitUntilSignalled() method. After the fields are populated, the user clicks on a Transmit Data button. The GUI event thread unblocks and then enters the deliverEventToListener() method. That method invokes the actionPerformed() method, which signals the worker thread, and immediately returns to the waitForNextEvent() method. The worker thread unblocks, leaves the waitUntilSignaled() method, and enters the gatherDataAndTransmit() method. The worker thread gathers the data, transmits it, and blocks it while waiting to read a confirmation message from the server. After reading the confirmation, the worker thread returns to the waitUntilSignalled() method.

Figure 1.2: The partitioning of the work between two threads.

By dividing the work between two threads, the GUI event-handling thread is free to handle other user-generated events. In particular, you might want another button, labeled Cancel Request, that would signal the worker thread to cancel the interaction with the server. If you had not used a worker thread to perform the interaction with the server, but simply had the GUI event thread do the work, the interruption activity triggered by the Cancel Request button would not be possible.

Simplify Object Modeling

Object-oriented analysis of a system before it is built can lead to a design requiring some of the objects to have a thread running within them. This kind of object can be thought of as active, as opposed to passive. A passive object changes its internal state only when one of its methods is invoked. An active object may change its internal state autonomously.

As an example, consider building a digital clock graphical component that displays the current system time in hours and minutes. Every 60 seconds, the minutes (and possibly the hours) displayed on this component will have to change. The simplest design is to have a thread running inside the clock component and dedicated to updating the digits when necessary. Otherwise, an external thread would have to continually check whether it is time to update a digit, in addition to performing its other duties. What if that external thread had to read data from an InputStream, and it was blocked, waiting for a byte for longer than a minute? Here, exploiting the benefits of multithreaded programming simplifies the solution.