Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The first way to customize a thread is to subclassThread
(itself aRunnable
object) and override its emptyrun
method so that it does something. Let's look at theSimpleThread
class, the first of two classes in this example, which does just that:The first method in thepublic class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } }SimpleThread
class is a constructor that takes aString
as its only argument. This constructor is implemented by calling a superclass constructor and is interesting to us only because it sets theThread
's name, which is used later in the program.The next method in the
SimpleThread
class is therun
method. Therun
method is the heart of anyThread
and where the action of theThread
takes place. Therun
method of theSimpleThread
class contains afor
loop that iterates ten times. In each iteration the method displays the iteration number and the name of theThread
, then sleeps for a random interval of up to 1 second. After the loop has finished, therun
method printsDONE!
along with the name of the thread. That's it for theSimpleThread
class. Let�s put it to use inTwoThreadsTest
.The
TwoThreadsTest
class provides amain
method that creates twoSimpleThread
threads:Jamaica
andFiji
. (If you can't decide on where to go for vacation, use this program to decide.)Thepublic class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } }main
method starts each thread immediately following its construction by calling thestart
method, which in turn calls therun
method. Compile and run the program and watch your vacation fate unfold. You should see output similar to this:Note how the output from each thread is intermingled with the output from the other. The reason is that both SimpleThread
threads are running concurrently. So bothrun
methods are running, and both threads are displaying their output at the same time. When the loop completes, the thread stops running and dies.Now let�s look at another example, the
Clock
applet, that uses the other technique for providing arun
method to aThread
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.