Thread stop不能用了

http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

http://www.cnblogs.com/gpcuster/archive/2010/01/18/1650273.html

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


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.


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 throw operation, 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);
    }

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. 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 start , stop and run methods:

    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.


Why are Thread.suspend and Thread.resume deprecated?

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.


What should I use instead of Thread.suspend and Thread.resume ?

As with Thread.stop , the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait . When the thread is resumed, the target thread is notified using Object.notify .

For example, suppose your applet contains the following mousePressed event handler, which toggles the state of a thread called blinker :

    private boolean threadSuspended;

    Public void mousePressed(MouseEvent e) {
        e.consume();

        if (threadSuspended)
            blinker.resume();
        else
            blinker.suspend();  // DEADLOCK-PRONE!

        threadSuspended = !threadSuspended;
    }

You can avoid the use of Thread.suspend and Thread.resume by replacing the event handler above with:

    public synchronized void mousePressed(MouseEvent e) {
        e.consume();

        threadSuspended = !threadSuspended;

        if (!threadSuspended)
            notify();
    }

and adding the following code to the "run loop":

                synchronized(this) {
                    while (threadSuspended)
                        wait();
                }

The wait method throws the InterruptedException , so it must be inside a try ... catch clause. It's fine to put it in the same clause as the sleep . The check should follow (rather than precede) the sleep so the window is immediately repainted when the the thread is "resumed." The resulting run method follows:

    public void run() {
        while (true) {
            try {
                Thread.currentThread().sleep(interval);

                synchronized(this) {
                    while (threadSuspended)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

Note that the notify in the mousePressed method and the wait in the run method are inside synchronized blocks. This is required by the language, and ensures that wait and notify are properly serialized. In practical terms, this eliminates race conditions that could cause the "suspended" thread to miss a notify and remain suspended indefinitely.

While the cost of synchronization in Java is decreasing as the platform matures, it will never be free. A simple trick can be used to remove the synchronization that we've added to each iteration of the "run loop." The synchronized block that was added is replaced by a slightly more complex piece of code that enters a synchronized block only if the thread has actually been suspended:

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }

In the absence of explicit synchronization, threadSuspended must be made volatile to ensure prompt communication of the suspend-request.

The resulting run method is:

    private boolean volatile threadSuspended;

    public void run() {
        while (true) {
            try {
                Thread.currentThread().sleep(interval);

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

Can I combine the two techniques to produce a thread that may be safely "stopped" or "suspended"?

Yes; it's reasonably straightforward. The one subtlety is that the target thread may already be suspended at the time that another thread tries to stop it. If the stop method merely sets the state variable (blinker ) to null, the target thread will remain suspended (waiting on the monitor), rather than exiting gracefully as it should. If the applet is restarted, multiple threads could end up waiting on the monitor at the same time, resulting in erratic behavior.

To rectify this situation, the stop method must ensure that the target thread resumes immediately if it is suspended. Once the target thread resumes, it must recognize immediately that it has been stopped, and exit gracefully. Here's how the resulting run and stop methods look:

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);

                synchronized(this) {
                    while (threadSuspended && blinker==thisThread)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

    public synchronized void stop() {
        blinker = null;
        notify();
    }

If the stop method calls Thread.interrupt , as described above, it needn't call notify as well, but it still must be synchronized. This ensures that the target thread won't miss an interrupt due to a race condition.


What about Thread.destroy ?

Thread.destroy has never been implemented. If it were implemented, it would be deadlock-prone in the manner of Thread.suspend . (In fact, it is roughly equivalent to Thread.suspend without the possibility of a subsequent Thread.resume .) We are not implementing it at this time, but neither are we deprecating it (forestalling its implementation in future). While it would certainly be deadlock prone, it has been argued that there may be circumstances where a program is willing to risk a deadlock rather than exit outright.


Why is Runtime.runFinalizersOnExit deprecated?

Because it is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. While this problem could be prevented if the class whose objects are being finalized were coded to "defend against" this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.

Further, the call is not "thread-safe" in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!

RC电路(一):微分|积分 的取值不同,会导致输出波形和输入波形之间的关系也不同,由此也会产生不同的应用。输出为0,随着电容充满电,运放-输入端得到的分压为正最大值,可等效成一个电压源,且电压不可突变,此时电流反向为最大值,开始充电时的容抗为0,电压不可突变则电压差为0,运放。开始充电时的容抗为0,电压不可突变则电压差为0,运放。输入端得到的分压也不可突变,随着电容放完电,于是。,因电容上电压不能突变(来不及充电,相当于短路,由上分析可得积分运算电路中,输出为运放的负最大峰值,随着电容充满电,输出为运放的正最大峰值,随着电容放完电, 阅读详情

相关推荐

AntV G6避坑指南:折叠树状图那些意想不到的BUG(附解决方案)

本文深入剖析了在React项目中使用AntV G6实现折叠树状图时,从图标错乱、数据同步到状态管理的常见BUG与解决方案。文章基于实战经验,详细解读了G6的内部机制,提供了从环境配置、自定义节点绘制到事件处理与性能优化的完整避坑指南,帮助开发者彻底解决折叠展开功能的疑难杂症。

wasm7browser的博客 257

利用Thread.stop完成方法执行超时中断

示例代码可以从github上获取https://github.com/git-simm/simm-framework.git 接上篇博客《FutureTask子线程取消执行的状态判断》 一、业务场景:   系统中存在多种场景并发操作事务执行时互锁的情况,导致任务积压,系统崩溃。先做了各场景业务的性能调整,但是并发互锁依然无法避免。于是开始考虑选取调用频繁的同步功能作为死锁的牺牲品...

asd00017的博客 333

从零到一:使用阿里云百炼搭建企业级 AI Agent 完全实战手册(2026超详细版)

本文是一份企业级AI Agent构建手册,主要面向企业技术负责人、AI产品经理和后端开发工程师。手册详细介绍了如何在阿里云百炼平台上搭建企业智能体应用的全流程,包括环境准备、知识库构建、智能体创建、工具集成、工作流编排等核心环节。重点内容包括: 准备工作:阿里云账号注册、百炼服务开通、免费额度领取、API Key管理 知识库构建:文档格式要求、内容优化原则、RAG系统搭建 智能体开发:Agent创建、工具集成、复杂业务工作流设计 生产部署:多渠道接入、监控运维、安全治理 成本控制:Token预算管理、选型决

u010323587的专栏 1109

Java线程学习记录(三)

线程停止 run 方法内没有sleep或wait方法时,停止线程 下面这段代码while中监听了interrupt的状态,如果不监听他是不会停止下来的。 public class RightStopThreadWithoutSleep implements Runnable { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Rig

Csea的博客 215

3.3V-1.8V电平转换测试、以TXS0108E、NPN,NMOS方案为例

上述两个模块都测试过,测试结果相似。信号发生器产生3.3Vpp/10K Hz 方波测试1.8V信号输出结果模块出现顶部失真,原因是因为电平转换芯片需要转换的正电压,转换的方波如果没有设置偏置,会导致信号源的方波电平小于电平转换的所需的触发电平导致波形顶部失真。偏置设置为1.65V输出波形正常。但是模块接上负载后波形又出现顶部失真!!!TXS0108采用弱上拉设计(内部约4 kΩ上拉电阻),其驱动能力类似开漏输出,依赖外部负载完成电平转换。

weixin_56838517的博客 2782

AI系统架构设计实战:AI应用架构师的深度指南

核心概念:AI系统架构是指设计和组织人工智能系统各个组件(包括数据、算法、计算资源、集成接口等)的结构框架,以及这些组件之间的交互方式和原则。它为AI应用提供了技术蓝图,决定了系统的性能、可扩展性、可维护性和可靠性。数据的本质:数据是对客观事物的符号表示,是可识别的、抽象的符号。在AI系统中,数据不仅是输入,也是系统学习和改进的基础。数据就像AI系统的"燃料",其质量和数量直接决定了AI系统的能力边界。

AI天才研究院 1201

停止线程的错误方法

1、被弃用的stop,suspend和resume方法 stop方法天生不安全,该方法终止所有未结束的方法,包括run方法。当线程被终止,立即释放被它锁住的所有对象的锁。这会导致对象处于一个不一致的状态。当线程要终止另一个线程时,无法知道什么时候调用stop方法是安全的,什么时候导致对象被破坏。所以被弃用了。 与stop不同,suspend不会破坏对象,它可以和resume方法配套使用,但但其还是有很多缺点,比如容易造成死锁等 2、用volatile设置boolean标记位 看似可行的使用vol

qq_56572867的博客 318

14、5G物理层的灵活解决方案:广义频分复用(GFDM)

广义频分复用(GFDM)作为一种高度灵活的5G物理层多载波调制方案,能够满足多样化应用场景的需求,包括高吞吐量的比特管道通信、低功耗高连接数的物联网、超低延迟的触觉互联网以及广覆盖的无线区域网。通过参数化配置,GFDM可适配LTE资源网格,实现与现有系统的兼容与共存。其支持多种解调方式、干扰消除技术、OQAM映射及预编码机制,兼具低带外发射、高频谱效率和强鲁棒性。GFDM还能统一描述OFDM、FBMC、FTN等多种经典与先进波形,成为5G及未来通信系统中极具潜力的通用波形框架。

gold8的专栏 108

java Thread 不捕获异常 默认处理逻辑

java Thread默认异常处理逻辑

当个码农写bug 361

OBC_开环扫频波特图拟合操作流程(结合 Simulink)

摘要: 本文详细介绍了基于Simulink的开环扫频波特图测试与拟合流程,适用于电源/控制系统(如LLC/PFC)的小信号分析。主要内容包括:1)前期准备(测试点选择、信号范围设定);2)Simulink建模方法(信号注入、数据记录);3)两种扫频方式(逐频正弦/Chirp扫频)的实现;4)MATLAB数据处理(FFT分析、传递函数拟合);5)线性分析工具使用技巧。重点强调了激励信号幅值控制、稳态数据采集及模型验证方法,并提供完整MATLAB脚本示例。该流程可有效获取系统频域特性,为控制器设计提供可靠依据。

Sumerking的博客 234

PyCharm配置SSH和SFTP远程连接服务器

关于这篇博文,主要因为公司企业都是通过本地测试,同步到服务器进行跑动,舍友看着同事丝滑的操作,让我做个教程。本着钻研的精神,写下了这篇博客记录 关于pycharm这个软件,只有专业版才有远程连接的这个配置,社区版没有(同事一再强调要专业版,学生认证还可申请免费) 关于SSH和SFTP都是一种协议 具体知识点补充可看我这篇文章: 【计算机网络】常见面试题集锦(全) SSH:提供安全通道进行远程登录 SFTP协议可以远程文件传输获取等,数据的安全传输主要由SSH连接提供

码农研究僧的博客 5538

为什么thread1停止执行了???

【代码】为什么thread1停止执行了???

忽然七日 629

生信技能53 - WisecondorX自动化批量npz转换和reference构建

wiseconrdoX分析CNV适用于CNVseq、NIPT和WGS等项目。

LittleComputerRobot的博客 466

为什么不能使用Thread.stop()方法?

从SUN的官方文档可以得知,调用Thread.stop()方法是不安全的,这是因为当调用Thread.stop()方法时,会发生下面两件事: 1. 即刻抛出ThreadDeath异常,在线程的run()方法内,任何一点都有可能抛出ThreadDeath Error,包括在catch或finally语句中。 2. 释放该线程所持有的所有的锁   当线程抛出ThreadDeath异常时,会导致

小雷的私人记事本 2478

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

java为什么不能用stop,【Java并发系列】为什么Thread.stop等方法被弃用

为什么Thread.stop被弃用?因为它本质上是不安全的。(使用Thread.stop)停止一个线程会导致它解锁所有已锁定的监视器。(当ThreadDeath异常传播到堆栈时,监视器被解锁。)如果之前由这些监视器保护的任何对象处于不一致的状态,其他线程现在可以以不一致的状态查看这些对象。这种对象被称为受损对象。当线程操作受损对象时,可能导致任意行为。这种行为可能是微妙的,难以察觉,也可能会比较明...

weixin_29114331的博客 734

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

2022-01-26 Android java 使用线程(Thread)自带的isInterrupted()方法来结束线程,不能用stop。

一、Thread.stop()方法来结束线程的运行是很危险,一般不建议使用stop()来停止线程;不安全的原因主要有:在程序调用Thread.stop()后会抛出ThreadDeatherror()错误。并释放子线程所持有的所有锁,会导致被保护数据呈现不一致性,此过程不可控。实际运行这么用app直接挂了。 二、java 使用线程(Thread)自带的isInterrupted()方法来结束线程。isInterrupted()判断是否被中断,并清除当前中断状态。 1、代码如下 ...

海月汐辰 1097

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

libreportparam2.dll无法继续执行代码_Java并发系列番外(1)——让Thread#stop方法无法终止你的线程...

众所周知,Thread 类有一个 stop 方法,可以用来终止线程。当然,这个方法连同 suspend,resume 方法一起都已经被弃用了。原因是 stop 方法终止线程过于暴力,不管被 stop 的线程在干什么,一旦被 stop 它就得立刻停止执行,然后释放锁,这是非常不安全的。那么,有没有办法,让被 stop 的线程继续执行,并且不释放锁呢?我写了一段代码,各位可以拿去试试:package ...

weixin_39634132的博客 570

线程组多次调用_Java线程的启动和终止

在Java中我们启动线程都是调用Thread类中的start()方法来启动,当线程处理完run()方法里面的逻辑后自动终止。但是在调用start()方法之前,我们需要先构建一个Thread对象,一般我们都是直接使用Thread类的构造函数来创建一个线程对象,Thread构造函数定义如下:public Thread() { init(null, null, "Thread-" + nextTh...

weixin_31978571的博客 108

python 强制结束线程的坑

网上流传了两种能强制结束线程的错误姿势 第一种:通过setDaemon来结束线程 http://www.cnblogs.com/jefferybest/archive/2011/10/09/2204050.html import threading import time def mythread(timeout,func): tHandle = threadin...

318

python强制结束线程_python 强制结束线程的坑

网上流传了两种能强制结束线程的错误姿势第一种:通过setDaemon来结束线程importthreadingimporttimedefmythread(timeout,func):tHandle= threading.Thread(target=func)tHandle.setDaemon(True)tHandle.start()tHandle.join(timeout)print 'timeou...

weixin_39663602的博客 446

停止线程方法尝试和总结

public static void main(String[] args) { log.error("主线程:{}", Thread.currentThread().getName()); InnerRunnable myRunnable = new InnerRunnable(); Thread thread1 = new Thr...

yinni11的博客 239

[Java]stop()不能用,如何停止线程?

/*线程的生命周期=================================================== 新的线程-----------> 运行) ---------> 销毁 new Thread() start() stop()或run()执行完成 在运行中,可能会:礼让yield() 下面三个方法不建议使用,定义时使用了Deprecated(不赞成)声明,会产生死

jsqdsq的博客 753

停止java服务器_Java停止服务器线程

以下代码是我的应用程序中的服务器代码:private int serverPort;private Thread serverThread = null;public void networkListen(int port){serverPort = port;if (serverThread == null){Runnable serverRunnable = new ServerRunnabl...

weixin_32176627的博客 377

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

【代码】Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?

jxchallenger的专栏 1049

java stop thread_Thread之九:stop

搞过Java线程的人都知道,stop这个方法是臭名昭著了,早就被弃用了,但是现在任然有很多钟情与他的人,永远都放不下他,因为从他的字面意思上我们可以知道他貌似可以停止一个线程,这个需求是每个搞线程开发的人都想要的操作,但是他并非是真正意义上的停止线程,而且停止线程还会引来一些其他的麻烦事,下面就来详细的介绍一下这个方法的历史:从SUN的官方文档可以得知,调用Thread.stop()方法是不安全的...

weixin_34797773的博客 395

Thread中的stop方法过时

搞过Java线程的人都知道,stop这个方法是臭名昭著了,早就被弃用了,但是现在任然有很多钟情与他的人,永远都放不下他,因为从他的字面意思上我们可以知道他貌似可以停止一个线程,这个需求是每个搞线程开发的人都想要的操作,但是他并非是真正意义上的停止线程,而且停止线程还会引来一些其他的麻烦事,下面就来详细的介绍一下这个方法的历史: 从SUN的官方文档可以得知,调用Thread.sto

shuaiAWP的专栏 2759
上一篇: Apache HTTP Server与Tomcat连接
下一篇: (下载)NSIS
O2AtomLife
博客等级 码龄19年 2粉丝 82原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值