java thread的stop,suspend,resume等方法废弃的原因

用Raspberry Pi Imager重装树莓派系统 这次在官网无意中看到他们出了一个Raspberry Pi Imager的工具,可以直接完成镜像烧录操作,于是就尝了个鲜。选择“编辑设置”按钮,会弹出具体的设置信息,有三个tab,第一个是General信息,包括用户名、密码、wifi和语言设置;后续的操作就和我当初第一次装树莓派系统的操作差不多,在此就不再赘述,有兴趣的朋友可以看我以前的博文。完成定制化设置后,点击“保存”按钮,软件回到前面的提示框,连续点击两个“是”,开始写入SD。第二个下拉框选择你要安装的OS,点击黄框所在的选项,可以挑选更多OS。 阅读详情

如下是官方文档,先贴上,抽时间翻译

Java

Why Are Thread.stopThread.suspend
Thread.resume and Runtime.runFinalizersOnExit Deprecated?


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被废弃了呢?

因为它是天生不安全的。停止一个线程会导致它解锁它所锁定的所有monitor(当一个ThreadDeath Exception沿着栈向上传播时会解锁monitor,如果这些被释放的锁所保护的objects有任何一个进入一个不一致的状态,其他将要访问该objects的线程也会以一种不一致的状态来访问这些objects。这种objects称为“被损坏了”。当线程对被损坏的objects上做操作时,可能会产生意想不到的结果,这些行为可能是很严重的,并且难以探测到,

不像其他 uncheck exceptionThreadDeath Exception静默的杀死进程,因此,用户不会被警告他的程序会崩溃,这会在“损坏”之后的任何时候发生,甚至几小时或者几天后。


Couldn't I just catch the ThreadDeath exception and fix the damaged object?

In theory, perhaps, but it would vastly complicate the task of writing correct multithreaded code. The task would be nearly insurmountable for two reasons:

  1. A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail,with this in mind.
  2. A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.

In sum, it just isn't practical.

我不能catch到这个ThreadDeath exception 然后修复被损坏的object吗

理论上,或许可以。但是它会极大地将多线程代码编写复杂化,以下两个原因,让这项工作变得几乎不可能完成:

1.一个线程会在几乎任何地方抛出ThreadDeath exception,考虑到这一点,所有的同步方法和代码块将必须进行详细的考察

2.线程可能在处理第一个异常的时候(在catch,finally语句块里)抛出第二个异常,处理语句必须将不得不重新开始反复如此直到成功,来保证这一过程的代码将会非常复杂。

总结一下,这是不切实际的。


What about Thread.stop(Throwable)?

In addition to all of the problems noted above, this method may be used to generate exceptions that its target thread is unprepared to handle (including checked exceptions that the thread could not possibly throw, were it not for this method). For example, the following method is behaviorally identical to Java's throwoperation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:

    static void sneakyThrow(Throwable t) {
        Thread.currentThread().stop(t);
    }

那么Thread.stop()方法是怎么回事?

除了上边提到的这些问题之外,这个方法会产生它的目标线程未准备好处理的异常(包括Checked exception,这种线程或许不会抛出的异常),例如,下面的方法在行为上是与java的 Throwoperation相同的,但是规避了编译器试图保证该调用方法已经声明了所有的它可能会抛出的所有Checkd Exception的行为。

   static void sneakyThrow(Throwable t) {
        Thread.currentThread().stop(t);
    }


What should I use instead of Thread.stop?

Most 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. (This is the approach that the Java Tutorial has always recommended.) To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).

For example, suppose your applet contains the following startstop and run methods:

如果不用Thread.stop(),我们应该使用什么方法?

大多数对stop方法的调用应该用指示目标线程是否应该停止运行的一些变量的简单代码来替换,目标线程应该定时的检查这些变量,当发现这些变量指示该线程应该停止运行时,有序地从它的run方法来return。(这是java tutorial中经常要求的方式)

    private Thread blinker;

    public void start() {
        blinker = new Thread(this);
        blinker.start();
    }

    public void stop() {
        blinker.stop();  // UNSAFE!
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
You can avoid the use of Thread.stop by replacing the applet's stop and run methods with:
    private 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();
        }
    }


How do I stop a thread that waits for long periods (e.g., for input)?

That's what the Thread.interrupt method is for. The same "state based" signaling mechanism shown above can be used, but the state change (blinker = null, in the previous example) can be followed by a call to Thread.interrupt, to interrupt the wait:

    public void stop() {
        Thread moribund = waiter;
        waiter = null;
        moribund.interrupt();
    }
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
    Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException as soon as it is able.


What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.


如何修复Windows卡在“正在准备Windows”的问题?这里有详细步骤 如何修复Windows卡在“正在准备Windows”的问题?这里有详细步骤。 阅读详情

相关推荐

【安徽理工大学】一文带你高分拿下计算机考研复试(85+的秘密)

一文带你高分拿下安徽理工大学计算机考研复试(85+的秘密)

猫天意的博客 1495

多线程为什么弃用stopsuspend

初始的java版本中定义了一个stop方法来终止一个线程还定义了一个suspend方法来阻塞一个线程,直到另一个线程调用resume方法。这两个方法Java SE 1.2之后就被弃用了,因为这两种方法都不安全,下面我们分别来讨论一下为什么不安全和应该怎样做才是安全的。   一、stop方法为什么不安全   其实stop方法天生就不安全,因为它在终止一个线程时会强制中断线程的执行,不管ru...

maxiaoyin111111的博客 929

YOLO26小目标检测实战:STAL标签分配+MuSGD优化,VisDrone数据集漏检率降50%

小目标检测是计算机视觉的经典难题,而VisDrone数据集小目标占比极高:数据集中小目标(像素面积<32×32)占比超过60%,且大量目标仅为几个像素,特征信息极度匮乏;背景复杂且干扰多:无人机航拍场景包含建筑物、树木、人群、车辆等复杂背景,小目标易被背景淹没;尺度变化与遮挡严重:同一目标在不同帧中尺度差异大,且小目标极易被其他目标遮挡;传统模型的固有缺陷标签分配策略(如ATSS、SimOTA)偏向大目标,小目标的正样本分配不足,导致模型对小目标不敏感;

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1158

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 Threa

lisuyibmd的专栏 1491

Java Thread Primitive Deprecation

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 mo...

chuilin9373的博客 258

Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?翻译

前面我们的学习笔记中讲解Thread类中一些废弃方法原因,同时又示例代码。 现在我们来翻译官方给出的文档Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?。   """本文是我学习Java多线程以及高并发知识的第一本书的学习笔记, 书名是&lt;&lt;Java多线程编程核心技术&gt;&gt;,作者是大佬...

you are sherlocked by me! 1223

java并发(四)终止线程的三种方式

java并发(四)终止线程的四种方式 线程属于一次性消耗品,在执行完run()方法之后线程便会正常结束了,线程结束后便会销毁,不能再次start,只能重新建立新的线程对象,但有时run()方法是永远不会结束的。 例如在程序中使用线程进行Socket监听请求,或是其他的需要循环处理的任务。在这种情况下,一般是将这些任务放在一个循环中,如while循环。当需要结束线程时,如何退出线程呢? 有三种方...

weixin_41932830的博客 487

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

转载:http://blog.csdn.net/DLite/article/details/4212915     翻译: dlite@163.com 原文 : Why Are Thread.stop, Thread.suspend,Thread.resume and Runtime.runFinalizersOnExit Deprecated? 为什么 Thread.st

asdqwt的专栏 606

废弃Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit

最近学习多线程的知识,看到API里说这些方法废弃了,就查了一下原因 Thread.stop 这个方法会解除被加锁的对象的锁,因而可能造成这些对象处于不一致的状态,而且这个方法造成的ThreadDeath异常不像其他的检查期异常一样被捕获。 可以使用interrupt方法代替。事实上,如果一个方法不能被interrupt,那stop方法也不会起作用。 Thread.suspend, ...

weixin_30633949的博客 252

Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?

Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated? Why is Thread.stop deprecated? Because it is inherently unsafe. Stopping a thread cause

zhangfei_jiayou的专栏 1148

Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated ?

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 propag...

weixin_30632883的博客 105

javaThread类中stop()和suspend()为何不推荐使用?

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 pro

火炬手 926

java终止正在运行的线程_Java再学习——停止一个正在运行的线程

关于这个问题,先了解一下Thread方法中被废弃的那些方法suspend(), resume(),stop()/stop(Throwable obj),destroy()首先,stop(Throwable obj)和destroy()方法在最新的Java中直接就不支持了,没必要去看了。我们只需瞧瞧suspend(), resume(), stop()这三个就行了;suspend()——让当前线...

weixin_35981295的博客 236

java多线程停止方式

Why AreThread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated? How to Stop a Thread or a Task 如何停止java线程

stalendp的专栏 739

cpu高 thread vm_Java并发编程笔记-Thread类常用方法详解

话不多说,先上图,先看看Thread类中的public方法Thread类所有public方法打扰了。。。构造器常用的构造器有Thread()、Thread(String name)、Thread(Runnable target),看构造器不难发现,Thread类实例化都是调用了init方法,看看init方法的实现,叭叭叭一大段讲了从SecurityManager拿到线程组以及权限校验, Thre...

weixin_31993699的博客 97

java终止线程_Java中终止线程的三种方法

Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 这些终止线程运行的方法已经被废弃,使用它们是极端不安全的!1.线程正常执行完毕,正常结束也就是让run方法执行完毕,该线程就会正常结束。但有时候线程是永远无法结束的,比如while(true)。2.监视某些条件,结束线程的不间断运行需要while()循环在...

weixin_36116139的博客 630

【转】javaThread方法介绍

原文:javaThread方法介绍 http://blog.csdn.net/seapeak007/article/details/53395609 这篇文章找时间分析一下!!!:http://blog.csdn.net/apei830/article/details/4503112 --------------------------------------------------...

weixin_30514745的博客 95

Android:Deprecated Thread methods are not supported

今天用Threadstop()方法终止线程时,报Deprecated Thread methods are not supported异常,翻了下资料发现Thread的有些方法已经被废弃Why isThread.stopdeprecated? Because it is inherently unsafe. Stopping a thread caus...

weixin_34072637的博客 148

FusionEvaluation.zip_图像融合_图像融合 指标_图像融合评价_指数加权_融合评价

几种图像融合评价指标,AG,EN,FMI,MI,Qab,Qw,SF,SSIM,即平均梯度AG、信息熵EN、特征互信息FMI、互信息MI、边缘信息保持量Qab、加权融合质量评价因子Qw、空间频率SF和相似性指数SSIM。能较好的描述图像融合结果,稳定性较好。

毛细管计算选型软件.zip

毛细管计算选型软件

上一篇: android屏幕适配原理
下一篇: 设置adapter的item的背景时 不能使用根布局的属性
MorSine
博客等级 码龄12年 20粉丝 41原创
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值