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 theThread
class and theRunnable
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 JavaThread
class. If you do this, your program will look much like the programs discussed earlier that use theMyFrame
extension ofFrame
. However, you may find that you are putting most of your substantive code into yourMyThread
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 itsstart
method is called, the system will, in turn, call yourrun
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 theThread
class to build a multi-thread application.Implements Runnable
A different approach implements theRunnable
interface 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
- Source Code for JDK Packages