img
Choosing an Approach
At this point, you might be wondering why Java has two ways to create child threads, and
which approach is better. The answers to these questions turn on the same point. The Thread
class defines several methods that can be overridden by a derived class. Of these methods,
the only one that must be overridden is run( ). This is, of course, the same method required
when you implement Runnable. Many Java programmers feel that classes should be
extended only when they are being enhanced or modified in some way. So, if you will not
be overriding any of Thread's other methods, it is probably best simply to implement
Runnable. This is up to you, of course. However, throughout the rest of this chapter, we
will create threads by using classes that implement Runnable.
Creating Multiple Threads
So far, you have been using only two threads: the main thread and one child thread. However,
your program can spawn as many threads as it needs. For example, the following program
creates three child threads:
// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home