为什么 Thread.stop和Thread.suspend等被废弃了?

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/30 21:08:05
为什么 Thread.stop和Thread.suspend等被废弃了?

为什么 Thread.stop和Thread.suspend等被废弃了?
为什么 Thread.stop和Thread.suspend等被废弃了?

为什么 Thread.stop和Thread.suspend等被废弃了?
停止一个线程会导致其解锁其上被锁定的所有监视器(监视器以在栈顶产生ThreadDeath异常的方式被解锁).如果之前被这些监视器保护的任何对象处于不一致状态,其它线程看到的这些对象就会处于不一致状态.这种对象被称为受损的 (damaged).当线程在受损的对象上进行操作时,会导致任意行为.这种行为可能微妙且难以检测,也可能会比较明显.不像其他未受检的(unchecked)异常, ThreadDeath 悄无声息的杀死及其他线程.因此,用户得不到程序可能会崩溃的警告.崩溃会在真正破坏发生后的任意时刻显现,甚至在数小时或数天之后线程可以在几乎任何地方抛出 ThreadDeath 异常.由于这一点,所有的同步方法和(代码)块将必须被考虑得事无巨细.线程在清理第一个 ThreadDeath 异常的时候(在 catch 或 finally 语句中),可能会抛出第二个.清理工作将不得不重复直到到其成功.保障这一点的代码将会很复杂.那怎么来终止一个线程呢,例如,假设你的 applet 包含了 start 、 stop 和 run 方法: private Thread blinker; public void start() { blinker = new Thread(this); blinker.start(); } public void stop() { blinker.stop(); // 容易产品死锁 } public void run() { Thread thisThread = Thread.currentThread(); while (true) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); } }为了避免使用 Thread.stop ,你可以把applet的stop和run方法替换成:rivate volatile Thread blinker; public void stop() { blinker = null; } public void run() { Thread thisThread = Thread.currentThread(); while (blinker == thisThread) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); } }为什么 Thread.suspend 和Thread.resume 被废弃了?