/**
* Thread.stop引起同步异常问题的代码样例。<br>
* 所以过期且不推荐使用。他会造成数据的不一致问题,引起垃圾数据。
*
* @author Administrator
*
*/
private static Object lock = new Object();
private static int number = 0;
private static String name = "Name0";
public static void main(String[] args) {
ThreadStop t = new ThreadStop();
t.start();
ThreadRun t2 = new ThreadRun();
t2.start();
// 输出为
// number=1
// name=Name0,
// 如果去掉stop,则输出正常为
// nunber=1
// name=Name11
t.stop();
}
static class ThreadRun extends Thread {
public void run() {
synchronized (lock) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("number=" + number);
System.out.println("name=" + name);
}
}
}
static class ThreadStop extends Thread {
public void run() {
synchronized (lock) {
number++;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
name = "Name" + number;
}
}
}
}
/*Why is Thread.stop deprecated?
为什么Thread.stop会过期?
all the monitors that it has locked. (The monitors are unlocked as the
ThreadDeath exception propagates up the stack.) If any of the objects
previously protected by these monitors were in an inconsistent state,
other threads may now view these objects in an inconsistent state.
Such objects are said to be damaged. When threads operate on damaged
objects, arbitrary behavior can result. This behavior may be subtle
and difficult to detect, or it may be pronounced. Unlike other
unchecked exceptions, ThreadDeath kills threads silently; thus, the
user has no warning that his program may be corrupted. The corruption
can manifest itself at any time after the actual damage occurs, even
hours or days in the future.
监控上的异常在堆栈传播)。如有任何以前被这些所锁保护的对象将处于不一致的状态,其他线
程现在可以看到不一致的状态。这类对象可以认定是被破坏的。当线程操作被破坏的对象时,可
能引发任何结果。此现象可能是微妙和难以察觉,也可以显着。不同于其他为检查的例外,
ThreadDeath悄悄地杀死线程,因此,用户没有收到任何警告,他的程序可能会损坏。问题可
以出现在任何时间后,实际损害发生,甚至在数小时或数天以后。
















