Java Reference
In-Depth Information
Let's look closely at this program. First,
MyThread
implements
Runnable
. This means
that an object of type
MyThread
is suitable for use as a thread and can be passed to the
Thread
constructor.
Inside
run( )
, a loop is established that counts from 0 to 9. Notice the call to
sleep( )
.
The
sleep( )
method causes the thread from which it is called to suspend execution for the
specified period of milliseconds. Its general form is shown here:
static void sleep(long
milliseconds
) throws InterruptedException
The number of milliseconds to suspend is specified in
milliseconds
. This method can throw
an
InterruptedException
. Thus, calls to it must be wrapped in a
try
block. The
sleep( )
method also has a second form, which allows you to specify the period in terms of mil-
liseconds and nanoseconds if you need that level of precision. In
run( )
,
sleep( )
pauses
the thread for 400 milliseconds each time through the loop. This lets the thread run slow
enough for you to watch it execute.
Inside
main( )
, a new
Thread
object is created by the following sequence of statements:
As the comments suggest, first an object of
MyThread
is created. This object is then used
to construct a
Thread
object. This is possible because
MyThread
implements
Runnable
.
Finally, execution of the new thread is started by calling
start( )
. This causes the child
thread's
run( )
method to begin. After calling
start( )
, execution returns to
main( )
, and it
enters
main( )
's
for
loop. Notice that this loop iterates 50 times, pausing 100 milliseconds
each time through the loop. Both threads continue running, sharing the CPU in single-CPU
systems, until their loops finish. The output produced by this program is as follows. Be-
cause of differences between computing environments, the precise output that you see may
differ slightly from that shown here: