Java Reference
In-Depth Information
In the above program, each of the two threads was carrying out exactly the same
task, which meant that each of them could be created from the same
Thread
class
and make use of exactly the same
run
method. In practice, of course, different
threads will normally carry out different tasks. If we want the threads to carry out
actions different from each other's, then we must create a separate class for each
thread (each with its own
run
method), as shown in the next example.
Example
In this example, we shall again create two threads, but we shall have one thread display
the message 'Hello' fi ve times and the other thread output integers 1-5. For the fi rst
thread, we shall create a class called
HelloThread
; for the second, we shall create class
CountThread
. Note that it is
not
the main application class (
ThreadHelloCount
, here)
that extends class
Thread
this time, but each of the two subordinate classes,
HelloThread
and
CountThread
. Each has its own version of the
run
method.
public class ThreadHelloCount
{
public static void main(String[] args)
{
HelloThread hello = new HelloThread();
CountThread count = new CountThread();
hello.start();
count.start();
}
}
class HelloThread
extends Thread
{
public void run()
{
int pause;
for (int i=0; i<5; i++)
{
try
{
System.out.println("Hello!");
//Again, introduce an element
//of randomness…
pause = (int)(Math.random()*3000);
sleep(pause);
}
catch (InterruptedException interruptEx)
{
System.out.println(interruptEx);
}
}
Search WWH ::
Custom Search