Java Reference
In-Depth Information
Your program always has at least one thread: the one created when the program begins execution. In a nor-
mal Java application program, this thread starts at the beginning of main() . With an applet, the browser is
the main thread. That means that when your program creates a thread, it is in addition to the main thread of
execution that created it. As you might have guessed, creating an additional thread involves using an object
of a class, and the class is java.lang.Thread . Each additional thread that your program creates is represen-
ted by an object of the class Thread , or of a subclass of Thread . If your program is to have three additional
threads, you need to create three such objects.
To start the execution of a thread, you call the start() method for the Thread object. The code that ex-
ecutes in a new thread is always a method called run() , which is public , accepts no arguments, and doesn't
return a value. Threads other than the main thread in a program always start in the run() method for the ob-
ject that represents the thread. A program that creates three threads is illustrated diagrammatically in Figure
16-3 .
FIGURE 16-3
If a class that you define to represent a thread in your program is to do anything, you must implement the
run() method for the class because the version inherited from the Thread class does nothing. Your imple-
mentation of run() can call any other methods you want. Figure 16-3 shows the main() method creating all
three threads, but that doesn't have to be the case. Any thread can create more threads.
Now here comes the bite: You don't call the run() method to start a thread, you call the start() method
for the object representing the thread, and that causes the run() method to be called. When you want to stop
the execution of a thread that is running, you must signal to the Thread object that it should stop itself by
setting a field that the thread checks at regular intervals, for example.
The reason you must start a thread in the way I have described is somewhat complex, but basically it
boils down to this: Threads are always owned and managed by the operating system, and only the operating
system can create and start a new thread. If you were to call the run() method yourself, it would simply
operate like any other method, running in the same thread as the program that calls it.
When you call the start() method for a Thread object, you are calling a native code method that causes
the operating system to initiate another thread from which the run() method for the Thread object executes.
 
 
Search WWH ::




Custom Search