Java Reference
In-Depth Information
// Let the main thread sleep for 3 seconds
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// Stop the thread
System.out.println("Going to set the stop flag to true...");
vv.stopThread();
}
}
Thread started...
Going to sleep...
Going to sleep...
Going to sleep...
Going to set the stop flag to true...
Thread stopped...
■
a
volatile
variable of
long
and
double
types is treated atomically for read and write purposes. recall that a
non-volatile variable of
long
and
double
types is treated non-atomically. that is, if two threads are writing two different
values, say
v1
and
v2
to a non-volatile
long
or
double
variable, respectively, your program may see a value for that
variable that is neither
v1
nor
v2
. however, if that
long
or
double
variable is declared
volatile
, your program sees the
value
v1
or
v2
at a given point in time. You cannot make array elements as
volatile
.
Tip
Stopping, Suspending, and Resuming a Thread
The
stop()
,
suspend()
, and
resume()
methods in the
Thread
class let you stop a thread, suspend a thread, and
resume a suspended thread, respectively. These methods have been deprecated because their use is error-prone.
You can stop a thread by calling the
stop()
method. When the
stop()
method of a thread is called, the JVM
throws a
java.lang.ThreadDeath
error. Because of throwing this error, all monitors locked by the thread being
stopped are unlocked. Monitor locks are used to protect some important shared resources (typically Java objects). If
any of the shared resources protected by the monitors were in inconsistent states when the thread was stopped, other
threads may see that inconsistent state of those resources. This will result in an incorrect behavior of the program.
This is the reason that the
stop()
method is deprecated; you are advised not to use it in your program.
How can you stop a thread without using its
stop()
method? You can stop a thread by setting a flag that the
running thread will check regularly. If the flag is set, the thread should stop executing. This way of stopping a thread
was illustrated in Listing 6-24 in the previous section.
You can suspend a thread by calling its
suspend()
method. To resume a suspended thread, you need to call its
resume()
method. However, the
suspend()
method has been deprecated because it is error-prone and it may cause a
deadlock. Let's assume that the suspended thread holds the monitor lock of an object. The thread that will resume the
suspended thread is trying to obtain the monitor lock of the same object. This will result in a deadlock. The suspended