Java Reference
In-Depth Information
Display 19.2
Threaded Version of
FillDemo
(part 3 of 3)
55
public
void
doNothing(
int
milliseconds)
56
{
57
try
58
{
59
Thread.sleep(milliseconds);
60
}
61
catch
(InterruptedException e)
62
{
63
System.out.println("Unexpected interrupt");
64
System.exit(0);
65
}
66
}
67
}
//End Packer inner class
68
}
We only need to explain the method
start
and we will be through with our expla-
nation. The method
start
initiates the computation (process) of the calling thread. It
performs some overhead associated with starting a thread and then it invokes the
run
method for the thread. As we have already seen, the run method of the class
Packer
in
Display 19.2 draws the circles we want, so the invocation
run()
packerThread.start( );
does draw the circles we want, because it calls
run
. Note that you do not invoke
run
directly. Instead, you invoke
start
, which does some other needed things and then
invokes
run
.
This ends our explanation of the multithreaded program in Display 19.2, but
there is still one, perhaps puzzling, thing about the class
Packer
that we should
explain. The definition of the class
Packer
includes no instance variables. So, why do
we need to bother with an object of the class
Packer
? Why not simply make all the
methods static and call them with the class name
Packer
? The answer is that the
only way to get a new thread is to create a new
Thread
object. The things inherited
from the class
Thread
are what the object needs to be a thread. Static methods do
not a thread make. In fact, not only will static methods not work, the compiler will
not even allow you to define run to be static. This is because
run
is inherited from
Thread
as a nonstatic method and that cannot be changed to static when overriding
a method definition. The compiler will not let you even try to do this without creat-
ing an object of the class
Packer
.