This section provides a tutorial example on how to create new threads with your own classes extended from the 'Thread' class. You need to override the run() method in your own classes.
The first way to create a new thread in a Java program is to:
Extend a new class out of the "Thread" class.
Define the run() method in the new class to override the run() method in the Thread class.
Instantiate a new object of the new class.
Call the start() method on the new object.
Here is a tutorial sample program showing you how to do this:
class HelloThread extends Thread {
public static void main(String[] a) {
HelloThread t = new HelloThread();
t.start();
System.out.println("Hello world! - From the main program.");
}
public void run() {
System.out.println("Hello world! - From a thread.");
try {
sleep(1000*60*60);
} catch (InterruptedException e) {
System.ut.println("Interrupted.");
}
}
}
Output:
Hello world! - From the main program.
Hello world! - From a thread.
A couple of things you should know about this program:
This program will run (actually sleep) for about one hour, after printing
those messages. So you may need to press Ctrl-C to terminate the program.
There will be actually two threads running in this program. The first one
is the main thread executing the all the statement in the main() method. The
second one is a sub-thread launched by the t.start() statement. The sub-thread
executes all the statements in the run() method.
Notice the order of the messages printed out on the console. It tells us
that the sub-thread took a little bit longer to run its first statement, after
it has been launched by the main thread.
A multi-threading program will not terminate until all its threads has
reached the end of their execution. In our example, the main thread will end
after printing its message. But the sub-thread will need about one hour to
execute the sleep() call statement. So the entire program will not terminate
until the sub-thread ends.
The run() method in the Thread is empty, so if you want a thread to do some work, you need to override the run()
method.