Java Reference
In-Depth Information
// Use the MsgThreadRunnable object in this case.
msg1.stopThread();
System.out.println ("Thread 1 cancelled" + run1);
System.out.println ("Thread 2 cancelled" + run2);
}
}
7. After compiling the program, you can execute it. Your results should look
like this:
Inside thread Thread-1
Inside thread Thread-0
Inside thread Thread-1
Inside thread Thread-1
Inside thread Thread-0
...
This will be followed by multiple displays of the thread execution mes-
sages. It will end with the completion messages:
This thread is stopping Thread-0
Thread 1 cancelledThread[Thread-0,5,main]
Thread 2 cancelledThread[Thread-1,5,main]
This thread is stopping Thread-1
R
EVIEWING THE
E
XERCISES
Let's review the samples you've created. Feel free to experiment by yourself.
Threads can be created either by extending
Thread
or implementing the
Runnable
interface. In the example, you used a class (
MsgThread
) that inherits
from
Thread
and another class (
MsgThreadRunnable
) that implements the
Runnable
interface.
The useful work in these two classes is performed in the
run()
method. In the
examples, you simply write to
System.out
, but in practice, a thread will perform
some useful task, such as printing a report or waiting for a user response.
The threads are stopped when the main class (HelloWorld) calls the
stopThread()
method.