|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The first way to customize a thread is to subclassThread(itself aRunnableobject) and to override its emptyrunmethod so that it does something. Let's look at theSimpleThreadclass, 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.format("%d %s%n", i, getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.format("DONE! %s%n", getName()); } }SimpleThreadclass is a constructor that takes aStringas its only argument. This constructor is implemented by calling a superclass constructor and is interesting only because it sets theThread's name, which is used later in the program.The next method in the
SimpleThreadclass is therunmethod: the heart of anyThreadand where the action of theThreadtakes place. Therunmethod of theSimpleThreadclass contains aforloop 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 one second. After the loop has finished, therunmethod printsDONE!along with the name of the thread. That's it for theSimpleThreadclass. Let's put it to use inTwoThreadsTest.The
TwoThreadsTestclass provides amainmethod that creates twoSimpleThreadthreads:JamaicaandFiji. (If you can't decide on where to go for vacation, use this program.)Thepublic class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } }mainmethod starts each thread immediately following its construction by calling thestartmethod, which in turn calls therunmethod. Compile and run the program and watch your vacation fate unfold. You should see output similar to that shown in the following figure.Note how the output from each thread is intermingled with the output from the other. The reason is that both
Output from two threads running concurrently.
SimpleThreadthreads are running concurrently. Thus, bothrunmethods 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
Clockapplet, which uses the other technique for providing arunmethod to aThread.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.