为什么Thread.stop会过期?一段引起同步异常问题的代码样例

本文通过一个示例展示了Thread.stop方法可能导致的数据不一致性问题。该方法会使线程突然终止并释放所有锁,导致其他线程可能看到不一致的数据状态,从而引发不可预测的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.java2000.net/p11400
先看一段stop引起同步异常的代码。
  1. package thread;

  2. /**
  3.  * Thread.stop引起同步异常问题的代码样例。<br>
  4.  * 所以过期且不推荐使用。他会造成数据的不一致问题,引起垃圾数据。
  5.  * 
  6.  * @author Administrator
  7.  * 
  8.  */
  9. public class ThreadStopTest {
  10.   private static Object lock = new Object();
  11.   private static int number = 0;
  12.   private static String name = "Name0";

  13.   public static void main(String[] args) {
  14.     ThreadStop t = new ThreadStop();
  15.     t.start();
  16.     ThreadRun t2 = new ThreadRun();
  17.     t2.start();
  18.     // 输出为
  19.     // number=1
  20.     // name=Name0,
  21.     // 如果去掉stop,则输出正常为
  22.     // nunber=1
  23.     // name=Name11
  24.     t.stop();
  25.   }

  26.   static class ThreadRun extends Thread {
  27.     public void run() {
  28.       synchronized (lock) {
  29.         try {
  30.           Thread.sleep(100);
  31.         } catch (InterruptedException e) {
  32.           e.printStackTrace();
  33.         }
  34.         System.out.println("number=" + number);
  35.         System.out.println("name=" + name);
  36.       }
  37.     }
  38.   }

  39.   static class ThreadStop extends Thread {
  40.     public void run() {
  41.       synchronized (lock) {
  42.         number++;
  43.         try {
  44.           Thread.sleep(50);
  45.         } catch (InterruptedException e) {
  46.           e.printStackTrace();
  47.         }
  48.         name = "Name" + number;
  49.       }

  50.     }
  51.   }
  52. }


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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值