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.langpackage. In particular, look at theThreadclass and theRunnableinterface.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
Threadclass. If you do this, your program will look much like the programs discussed earlier that use theMyFrameextension ofFrame. However, you may find that you are putting most of your substantive code into yourMyThreadclass.A Second approach, which many believe is preferable for most applications, is to implement the
Runnableinterface 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 itsstartmethod is called, the system will, in turn, call yourrunmethod. 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
Threadclass to build a multi-thread application.Implements Runnable
A different approach implements the
Runnableinterface to build a multi-thread application.
References
References useful for this discussion include the following:
- Sun's Java Development Kit (JDK)
- Sun's Java API
- Java API Class Hierarchy