In Java, there are two ways to create threaded programs:
class MyThread extends Thread {
......
}
class MyThread implements Runnable {
......
}Thread class, because you must extend some other class.
In programming applets, for example, you must extend the Applet class.
Remember that Java does not support multiple inheritance. In those cases
where it is not possible to extend the Thread class, you need to
implement the Runnable interface.
In this lab we are using the first approach, that extends the Thread class.
To create new threads in this case, simply use:
MyThread t = new MyThread();
The Thread class has three primary methods
that are used to control a thread:
public void start()
public void run()
public final void stop()
The start() method prepares a thread
to be run; the run() method actually
performs the work of the thread - it serves as the main routine for the
thread; and the stop() method
halts the thread. The thread dies when the run()
method terminates or when the thread's stop() method is invoked.
The class that extends Thread must redefine the
run() method of Thread.
To start the thread actually running, you do not invoke the run() method.
Rather, you invoke the start() method on your object:
The t.start();run() method is called automatically at runtime as necessary, once
you have called start(). To stop a thread, simply call
t.stop();
public Thread(String name)
This is normally called from the constructor of a subclass (your own), like this:
class MyThread extends Thread {
MyThread(String name) {
super(name);
}
public void run() {
System.out.println(this.getName());
...
}
}
The getName() method of the Thread class
returns the name of the thread.
The following program now distinguishes the output of different threads:
public class NamedThreadsTest {
public static void main(String[] args) {
MyThread first = new MyThread("First ...");
MyThread second = new MyThread("Second ...");
MyThread third = new MyThread("Third ...");
first.start();
second.start();
third.start();
}
}
javathreads in your Unix account and download this
simple TestThread.java multithreaded
code into the javathreads directory. Compile and run the
example and observe the output.