〖JAVA经验〗JAVA技巧(为什么Thread.stop会过期?)

先看一段stop引起同步异常的代码。

package thread;

/**

* Thread.stop引起同步异常问题的代码样例。

* 所以过期且不推荐使用。他会造成数据的不一致问题,引起垃圾数据。

*/

public class ThreadStopTest {

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会过期?

Because it is inherently unsafe. Stopping a thread causes it to unlock 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悄悄地杀死线程,因此,用户没有收到任何警告,他的程序可能会损坏。问题可以出现在任何时间后,实际损害发生,甚至在数小时或数天以后。

一起交流学习请访问:Tore_m_1206686_21115_1_1.html”>http://www.shangxueba.com/sTore_m_1206686_21115_1_1.html

穿别人的鞋,走自己的路,让别追去吧

〖JAVA经验〗JAVA技巧(为什么Thread.stop会过期?)

相关文章:

你感兴趣的文章:

标签云: