Java Threads

In this discussion, we consider Java threads. The discussion will not cover all aspects of threads supported in Java, but rather focus on those needed to implement multi-threaded clients and servers.

The relevant classes are contained in the java.lang package. In particular, look at the Thread class and the Runnable interface.

If you wish to run the applications discussed below, you may copy them from the directory for this discussion onto your system and run them there.


Overview

There are two basic strategies for implementing multi-threaded programs. First, you may extend the Java Thread class. If you do this, your program will look much like the programs discussed earlier that use the MyFrame extension of Frame. However, you may find that you are putting most of your substantive code into your MyThread class.

A Second approach, which many believe is preferable for most applications, is to implement the Runnable interface in your program. One of the most important and most deliberate decisions by the designers of Java was to include only single inheritance. This means that your classes can extend at most one class. Some languages, such as C++, allow classes to extend more than one class, but at considerable expense in terms of complexity. However, since you may wish to have your program do many of the things found in two classes, the Java developers provided the mechanism of Interface that provides many of the benefits of multiple inheritance but without some of its liability.

An Interface is an abstract specification for a set of methods. By stating in the declaration of a class that it implements Runnable, you commit to implement certain specified methods. In return, you receive certain guarantees by the Java Virtual Machine. For example, it guarantees with respect to classes that implement the Thread interface, that when instantiated and its start method is called, the system will, in turn, call your run method. And, of course, you get all of the other functionality associated with threads.


Implementations

In this section, we will look at the two implementations described above.

Extends Thread

The first implementation extends the Thread class to build a multi-thread application.

Implements Runnable

A different approach implements the Runnable interface to build a multi-thread application.

References

References useful for this discussion include the following: