我们知道像stop、suspend这几种中断或者阻塞线程的方法在较高java版本中已经被标记上了@Deprecated过期标签,那么为什么她们曾经登上了java的历史舞台而又渐渐的推出了舞台呢?
到底是人性的扭曲还是道德的沦丧呢,亦或是她们不思进取被取而代之呢,如果是被取而代之,那么取而代之的又是何方人也,本文我们将一探究竟。
一、stop的落幕
首先stop方法的作用是什么呢,用java源码中的一句注释来了解一下:Forces the thread to stop executing.
,即强制线程停止执行,'Forces’似乎已经透漏出了stop方法的蛮狠无理。
那么我们再看看java开发者是怎们解释stop被淘汰了的:
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the uncheckedThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.
我们从中可以看出以下几点:
- stop这种方法本质上是不安全的
- 使用Thread.stop停止线程会导致它解锁所有已锁定的监视器,即直接释放当前线程已经获取到的所有锁,使得当前线程直接进入阻塞状态
我们举例来看一下上边提到的两点:
public static void main(String[] args) throws InterruptedException {
Object o1=new Object();
Object o2=new Object();
Thread t1=new Thread(()->{
synchronized (o1)
{
synchronized (o2)
{
try {
System.out.println("t1获取到锁");
Thread.sleep(5000);