Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?(源码学习)


一、Thread.stop

Why is Thread.stop deprecated?

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.

为什么Thread.stop是不推荐的方法?

因为他本质上是不安全的。停止一个线程会引发该线程锁定的全部监视器解锁。( 解锁引发ThreadDeath异常)如果以前受这些监视器保护的对象处于不一致的状态,其他线程可能会在不一致的状态下查看这些对象。这些对象被称为损坏。使用这些损坏的对象时,任何行为都可能发生。这种行为可能是微妙的,难以检测,或它可能是明显的。不像其他的未检查异常,ThreadDeath悄悄地杀死线程;因此,用户没有警告,他的程序可能被损坏。错误可以在实际损害发生后的任何时间,甚至在未来几小时或几天内表现出来。

How do I stop a thread that waits for long periods (e.g., for input)?如何在等待一段时间后停止一个线程
public void stop() {
    Thread moribund = waiter;
    waiter = null;
    moribund.interrupt();
}

tricks:What if a thread doesn't respond to Thread.interrupt?如果线程不回应Thread.interrupt怎么办?在while自旋锁中判断interrupt

package extthread;
public class MyThread extends Thread {
    @Override
    public void run() {
            while (true) {
                if (this.isInterrupted()) {
                    System.out.println("停止了!");
                    return;
                }
                System.out.println("timer=" + System.currentTimeMillis());
            }
    }
}
运行类Run.java代码如下:
package test.run;
import extthread.MyThread;
public class Run {
    public static void main(String[] args) throws InterruptedException {
        MyThread t=new MyThread();
        t.start();
        Thread.sleep(2000);
        t.interrupt();
    }
}

二、Thread.suspend(暂停)、Thread.resume(恢复)

Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.

suspend本质上容易导致死锁,如果目标线程执行suspend,则其他线程无法获得该资源,直到resume,如果要恢复目标线程的线程试图在调用“恢复”之前锁定该监视器,则死锁。

应该用notify和wait代替suspend和rusume



你可能感兴趣的:(源码学习,java多线程)