Java Reference
In-Depth Information
Creating Threads
Your program always has at least one thread: the one created when the program begins execution. With
a 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 you use is java.lang.Thread . Each additional thread that your
program creates is represented by an object of the class Thread , or of a subclass of Thread . If your
program is to have three additional threads, you will 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
executes 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 object that represents the thread. A program that creates three threads is
illustrated diagrammatically here:
A Console Program that Spawns Three Threads
Program
main(){
thread1
// Create thread1
// Start thread1
run(){
thread2
// Code for the
// thread...
}
// Create thread2
// Start thread2
run(){
// Code for the
// thread...
}
thread3
// Create thread3
// Start thread3
}
run(){
// Code for the
// thread...
}
All four threads can be
executing concurrently
For a class representing a thread in your program to do anything, you must implement the run()
method as the version defined in the Thread class does nothing. Your implementation of run() can
call any other methods you want. Our illustration shows main() 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 call the stop() method for the Thread object.
The reason for this is somewhat complex but basically boils down to this: Threads are always owned
and managed by the operating system and a new thread can only be created and started by the
operating system. 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.
Search WWH ::




Custom Search