Java Reference
In-Depth Information
suspend( )
,
resume( )
, and
stop( )
, which are methods defined by
Thread
, to pause, re-
start, and stop the execution of a thread. They have the following forms:
final void resume( )
final void suspend( )
final void stop( )
While these methods seem to be a perfectly reasonable and convenient approach to man-
aging the execution of threads, they must no longer be used. Here's why. The
suspend( )
method of the
Thread
class was deprecated by Java 2. This was done because
suspend( )
can sometimes cause serious problems that involve deadlock. The
resume( )
method is also
deprecated. It does not cause problems but cannot be used without the
suspend( )
method
as its counterpart. The
stop( )
method of the
Thread
class was also deprecated by Java 2.
This was done because this method too can sometimes cause serious problems.
Since you cannot now use the
suspend( )
,
resume( )
, or
stop( )
methods to control a
thread, you might at first be thinking that there is no way to pause, restart, or terminate a
thread. But, fortunately, this is not true. Instead, a thread must be designed so that the
run(
)
method periodically checks to determine if that thread should suspend, resume, or stop its
own execution. Typically, this is accomplished by establishing two flag variables: one for
suspend and resume, and one for stop. For suspend and resume, as long as the flag is set to
“running,” the
run( )
method must continue to let the thread execute. If this variable is set
to “suspend,” the thread must pause. For the stop flag, if it is set to “stop,” the thread must
terminate.
The following example shows one way to implement your own versions of
suspend( )
,
resume( )
, and
stop( )
: