A thread shoud not be controlled directly by other threads

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

目录

1.Deprecated methods

2.suspend() & resume()

3.destroy()

4.stop()


1.Deprecated methods

In mulitple-thread application, threads may communicate with each other to share(write, read or lock) common memory. But any thread usually shoudn't directly make other thread suspended ,stopped or destroyed, though the ability is provided with instance method suspend(), resume(), stop() and destroy() in class Thread.

In java api document, such method suspend(), resume(), destroy() and stop() are deprecated. Let's check out the following examples to find out why.

2.suspend() & resume()

public class Suspend {
    
    public static Object lock = new Object();  
    
    public static class CalculateTaskThread extends Thread{        
        @Override
        public void run() {            
            synchronized (lock) {                
                // ... do calculate task, will cost 20 seconds
                Thread.sleep(20 * 1000);
            }
        }
    }
    
    public static void main(String[] args) {
        
        Thread calculateTaskThread = new CalculateTaskThread();
        calculateTaskThread.start();
        
        // sleep 10 senconds to wait calculateTaskThread to run.
        Thread.sleep(10 * 1000);
        
        // suspend calculateTaskThread
        calculateTaskThread.suspend();
        
        // aquire lock to do something
        synchronized (lock) {            
            // do something
        }        
        // resume calculateTaskThread
        calculateTaskThread.resume();
    }
}

In the java example aboved, there are two threads: calculateTaskThread and main thread, when calculateTaskThread starts and executes calculate task, main thread invoke suspend() to suspend calculateTaskThread, then main thread want to aquire to do something, but calculateTaskThread are holding the lock while being suspended, so main thread can not aquire lock and keep waitting. That causes two threads are waitting indefinitely, also called dead-lock.

Tips: If your application had severe dead-lock problem, you can use jstack tool provided by jdk to analyse thread with informations about thread state, monitor lock and etc. For example , I ran the codes above in my portable computer, then I use jstack to print informations of threads that have started.

From the informations printed in console, we can see that main thread are blocked waiting to lock object with address number <0x00000000d6e34bf8>, but such obejct <0x00000000d6e34bf8> is locked by calculateTask and calculateTask is in TIME_WAITING, so main thread will not get lock.

There is the other reason for deprecating suspend(), resume(), let's see codes written as follows.

public class Suspend {
    
    public static Object lock = new Object();    
    
    public static class CalculateTaskThread extends Thread{
        
        @Override
        public void run() {            
            synchronized (lock) {                
                // suspend itself
                suspend();
            }
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        
        Thread calculateTaskThread = new CalculateTaskThread();        
        
        synchronized (lock) {            
            calculateTaskThread.start();
            
            // sleep 10 senconds to wait calculateTaskThread to run.
            Thread.sleep(10 * 1000);
            
            // resume calculateTaskThread
            calculateTaskThread.resume();
        }
    }
}

In the example above, main thread holds lock and starts calculateTaskThread, then the calculateTaskThread starts to run and wait for aquiring lock to suspend itself, but then main thread resume calculateTaskThread before calculateTaskThread actually suspends itself, so the resume action doesn't work. When the main thread exits to return lock to calculateTaskThread, calculateTaskThread will suspend itself forever. Call order between suspend() and resume() must be strict avoiding terrible result.

3.destroy()

This method was never implemented. It was original designed to detroy this thread without any cleanup. Any monitors it held would have remained lock. it woud be deadlock-prone in much the manner of suspend(). If the target thread held a lock protecting a critical system resources when it was detroyed, no thread could ever access the resources again. If another thread ever attempt to lock this resource, deadlock would result.

4.stop()

stop() causes the thread to unlock all monitors that it has held, If any of the objects previously protected by these monitors were in a inconsistent state, these damaged objects would become visible to other threads, potentially result in arbitrary behavior.

 👉👉👉 自己搭建的租房网站:全网租房助手,m.kuairent.com,每天新增 500+房源

2026年最新湛江市公交线路矢量数据.zip 数据格式:shp 数据坐标:GCJ02 数据更新时间:2026年9月 公交线路来源:8684网站 https://8684.com.cn/ 站点数据来源:高德API接口 数据打开方式:QGIS或Arcgis 站点数据字段:名称、序号、对应线路、几何信息 线路数据字段:名称、类型、起点、终点、开始时间、结束时间、起步价、全价、长度、公司、几何信息 立即下载

相关推荐

蒙氏儿童绘本馆绘本租赁管理系统-开题.doc

蒙氏儿童绘本馆绘本租赁管理系统-开题

正确使用字节流按照指定字符编码获取字符串

在实际工作中,我们经常会遇到读取文本或网络中的内容,但是由于编码格式的不统一,往往得到的结果总是一团乱码,这就需要将文本按照它原本保存的编码解析成正确的内容。下面这段代码使用了字节按照指定编码获取字符串,可能很多人也使用它,其实呢这段代码是错误的,如果使用的时候感觉一切正常的话,那只能说你运气挺好。 private String inputStreamToString(InputStream i

Turnhead的专栏 6401

国央企如何利用数字化手段优化创新项目内部决策?.docx

科易网基于40亿+科创知识图谱数据库,深度探索AI技术在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,研究科技创新领域的AI+数智化解决方案,推动科技创新与产业创新智能化发展。

java源码英文注释翻译和解析(基于jdk1.7)-集合篇-Iterable&Iterator(接口)

目录 1.接口概述: 2.源码翻译&amp;解析: 1.接口概述: Iterable:该接口只有一个方法iterator(),此方法作用是获取一组元素的迭代器。当一个类实现了该接口,可以用foreach语法糖遍历该类元素,在编译阶段foreach语法糖会转换为调用iterator()方法获取迭代器遍历元素。容器根接口Collection继承Iterable,意味着所有...

Turnhead的专栏 1884

java泛型探秘(二):泛型擦除

目录 一.泛型擦除是什么 二. 为什么要擦除 三. 擦除造成的限制 1. 特殊的rawType 2. 不支持原始类型 3. 不能用占位符创建实例或数组 4. 不能创建泛型数组 一.泛型擦除是什么 java泛型是编译期的泛型,不是运行时的泛型 java语言是跨平台的,每个平台都有对应的JVM(java虚拟机),编写的java源码不能直接在JVM中运行,能在...

Turnhead的专栏 1623

为什么Collection接口的remove方法参数类型是Object而不是类型参数(泛型)

在jdk1.2版本之后的Collection接口被泛型化了,add方法的参数类型为泛型,remove方法的参数类型依然为Object,既然add添加元素时严格限制类型,保证了列表元素结构不被破坏,remove删除却放宽了类型限制,有点不合常理,查阅资料,了解到这样做的原因既有逻辑上的考虑,也有技术上的妥协,可能当时没有更好的解决办法。 一、从remove方法含义上看 ...

Turnhead的专栏 1621

Lock vs Semaphore vs Condition Variable vs Monitor(中文)

在多线程(并发)程序中,多个线程会访问同一个共享内存,为了避免产生一些奇怪的结果,这些线程应该按照合适的顺序访问共享内存,这个过程称为同步(synchronization)。仅仅保持同步还不够,为了让同步更加高效,多个线程互相之间保持交流。 1.Critical Section(CS) 临界区(Critical section)是程序的一段代码块,临界区不能被多个线程在同一时间访问,临界区的访问是互斥的,某一时刻最多只有一个线程能进临界区。 2.Lock Lock提供了一种互斥的方式,Lo...

Turnhead的专栏 1430

重识JVM(1)- 冯诺依曼体系

目录 1. 引言 2. 简介 3. 冯诺依曼体系 4. CPU组成和工作流程 5. JVM组成和工作流程 6. 总结 7. 思考 1. 引言 学习java这门语言,最先学到的除了一些基础的语法知识,还有关于jvm的一些东西,像堆栈、方法区、垃圾回收,站在巨人的肩膀上,我们只需要对jvm有个大概的了解就行了,可是仅靠书本和网络...

Turnhead的专栏 869

List接口英文注释翻译

一个有序的容器(也被称为序列)。接口使用者可以精确控制列表中每个元素的插入位置。用户可以通过整数索引 (列表中的位置)访问元素,还能查找列表中的元素。 不像集合,列表通常允许重复元素。更正式点的说法是,列表通常允许满足e1.equals(e2)这样的e1和e2元素对, 另外如果允许空元素通常也会允许多个空元素。有人想通过当使用者尝试插入重复元素时抛出运行时异常的方式...

Turnhead的专栏 743

volatile官方文档解释

一、描述: 官方文档中对volatile中描述中,写到: This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not...

Turnhead的专栏 589

重识JVM(2) - JAVA内存模型

目录 一、概念和误解 二、疑问 三、计算机的内存模型 3.1. 内存顺序和程序顺序 3.2. SC内存模型 3.3. TSO内存模型 3.4. 其他内存模型 3.5.JAVA内存模型 3.6. volatile实现原理 一、概念和误解 java内存模型,英文全称为java memory model,简称JMM。网上大部分关于java内存模型的资料都是关于堆栈...

Turnhead的专栏 537

Lock vs Semaphore vs Condition Variable vs Monitor

目录 1. Critical Section(CS) 2. Lock 3. Semaphore 4. Condition variable 5. Monitor 6. Summary In mutil-threads (concurrent) programing, two or more threads have access to a shared memory, for avoiding confusing results, these threads should acces...

Turnhead的专栏 465

java泛型探秘(一):泛型是什么

目录 一. 泛型基本概念 二. java泛型是什么&为什么使用泛型 三. java泛型的继承关系 一. 泛型基本概念 在维基百科上泛型是用这样一句话定义的: Generic programming is a style of computer programming in which algorithms are written in terms of types to...

Turnhead的专栏 463

ThreadLocal原理的秘密

目录 1. ThreadLocal描述 2. 认识ThreadLocalMap 3. 神奇的数字 4.注意 1. ThreadLocal描述 ThreadLocal保证了每个线程都有自己独享的变量,不用考虑并发同步的问题。通常情况下,ThreadLocal类型的变量被建议声明为static,即使多个线程调用多次,该变量也只会初始化一次。ThreadLocal使用起来很简单、方便,但非常值得弄清ThreadLocal的实现原理。 2. 认识ThreadLocalMap 在ThreadLo.

Turnhead的专栏 386

Producer-Consumer solution using wait(), notify(), park() and unpark()

1. Introduce In java, mutil-threads are used everywhere, applicationsnot only take advantages of mutil-threads improving efficiency, but also encounter some confusing problems especially when threads are not synchronized correctly. Fortunately, java prov.

Turnhead的专栏 286

What is thread in java and how its methods behave

1. What is Thread As in oracle java specification, thread is one of two basic units of execution, the other is process. Process was present prior to thread, we can refer to one process as an application. When an application is running, the resources alloc

Turnhead的专栏 206

The secret of ThreadLocal

ThreadLocal variable guareente each thread has own variable without thinking about synchronization. Usually threadlocal is d eclared static to be initialized only once whenever thread access it. We can easily use threadlocal in programm, but it is worth t

Turnhead的专栏 204

DellSupportAssistLauncher.exe

DellSupportAssistLauncher.exe

国央企如何科学评估创新技术的战略价值?.docx

科易网基于40亿+科创知识图谱数据库,深度探索AI技术在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,研究科技创新领域的AI+数智化解决方案,推动科技创新与产业创新智能化发展。

上一篇: What is thread in java and how its methods behave
下一篇: Producer-Consumer solution using wait(), notify(), park() and unpark()
祥先生
博客等级 码龄14年 48粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值