The Start, Run, and Stop Methods
class defines a method called
. This method will create a brand new thread, which then runs a method called
. After the
method completes, the
class will tidy up and terminate the thread safely. The
method returns control to the calling routine almost immediately, and the thread runs in parallel with the remainder of the code being executed. In some ways, the
method could be considered the thread equivalent of a
method. Parameters cannot be passed to it, however, and so the threaded class must be programmed to receive any required parameters either through the constructor or by a special method, executed before the call to start. It often is beneficial to pass a reference to the parent class as a means of providing communication from the thread to the rest of the project.
The only remaining method of significance from
stop(), which is used to terminate an executing thread. This method may be called from any class that wishes to destroy the thread and that has a reference to it. (See the sidebar "More on the Stop Method.") Taking Threads Farther
As can be seen, the Thread class is very easy to derive from and use. The example may be simple, but it is easy to conceive many ways that threads can be used. Imagine if a Web server didn't farm out incoming requests to new threads, and Web page requests had to be processed one at a time!
Several years ago I developed a system to analyze texts. In this system, a lot of processing was performed without requiring user assistance. As a consequence, users were effectively prevented from clicking any buttons (such as "Help," "About," etc.), as the system was so busy. By moving the main loop of the program into a separate threadwhich allowed the user interface to get some CPU timeI was able to reinstate the use of other events without affecting the program's logic or its results. At that point, I was able to leverage threads in many ways to improve the system. For example, in the original application, a particular class created a window that took some time to draw and hence was slow to appear. This too was moved into its own thread, and, although it didn't draw any faster, it permitted the user to perform other actions while the class created its window silently in the background.
I used other threads to receive incoming messages via TCP/IP socketsone for user messages and another for system commands. This permitted information to be silently retrieved from the system while still servicing the user. The usefulness of threads has no end. A thread may be used to simulate a timerthe thread simply sleeps for the duration of a specified time interval, and then finally notifies other threads that the timer has expired, for example.
The flexibility of threads in Java and the ease with which they are created gives further testimony to the usefulness and elegance of Java.