如何终止一个线程
如何终止一个线程
是使用 thread.stop() 吗?
public class ThreadDemo extends Thread{@Overridepublic void run() {try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("this is demo thread :"+Thread.currentThread().getName());}public static void main(String[] args) throws InterruptedException {ThreadDemo t = new ThreadDemo();t.start();System.out.println("this is main thread :"+Thread.currentThread().getName());t.stop();}
}
实际代码中的stop方法是不建议使用的:
t.stop ();
Java 的rt.jar 包中的Thread类的 stop() 源码:
/*** Forces the thread to stop executing.* <p>* If there is a security manager installed, its <code>checkAccess</code>* method is called with <code>this</code>* as its argument. This may result in a* <code>SecurityException</code> being raised (in the current thread).* <p>* If this thread is different from the current thread (that is, the current* thread is trying to stop a thread other than itself), the* security manager's <code>checkPermission</code> method (with a* <code>RuntimePermission("stopThread")</code> argument) is called in* addition.* Again, this may result in throwing a* <code>SecurityException</code> (in the current thread).* <p>* The thread represented by this thread is forced to stop whatever* it is doing abnormally and to throw a newly created* <code>ThreadDeath</code> object as an exception.* <p>* It is permitted to stop a thread that has not yet been started.* If the thread is eventually started, it immediately terminates.* <p>* An application should not normally try to catch* <code>ThreadDeath</code> unless it must do some extraordinary* cleanup operation (note that the throwing of* <code>ThreadDeath</code> causes <code>finally</code> clauses of* <code>try</code> statements to be executed before the thread* officially dies). If a <code>catch</code> clause catches a* <code>ThreadDeath</code> object, it is important to rethrow the* object so that the thread actually dies.* <p>* The top-level error handler that reacts to otherwise uncaught* exceptions does not print out a message or otherwise notify the* application if the uncaught exception is an instance of* <code>ThreadDeath</code>.** @exception SecurityException if the current thread cannot* modify this thread.* @see #interrupt()* @see #checkAccess()* @see #run()* @see #start()* @see ThreadDeath* @see ThreadGroup#uncaughtException(Thread,Throwable)* @see SecurityManager#checkAccess(Thread)* @see SecurityManager#checkPermission* @deprecated 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 unchecked* <code>ThreadDeath</code> 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 <code>stop</code> 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 <code>interrupt</code> method should be used to* interrupt the wait.* For more information, see* <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why* are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.*/@Deprecatedpublic final void stop() {SecurityManager security = System.getSecurityManager();if (security != null) {checkAccess();if (this != Thread.currentThread()) {security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);}}// A zero status value corresponds to "NEW", it can't change to// not-NEW because we hold the lock.if (threadStatus != 0) {resume(); // Wake up thread if it was suspended; no-op otherwise}// The VM can handle all thread statesstop0(new ThreadDeath());}
源码中标注了已弃用,并且给出来详细的解释和说明:
已弃用
这种方法本质上是不安全的。使用thread.stop停止线程会导致它解锁它锁定的所有监视器(这是未选中的ThreadDeath异常向堆栈上传播的自然结果)。
如果以前受这些监视器保护的任何对象处于不一致状态,则其他线程会看到损坏的对象,从而可能导致任意行为。stop的许多用法应该被简单地修改一些变量以指示目标线程应该停止运行的代码所取代。
目标线程应该定期检查该变量,如果该变量指示要停止运行,则以有序的方式从其运行方法返回。
如果目标线程长时间等待(例如,在条件变量上),则应使用中断方法中断等待。
操作系统在执行stop时,并不知道Java当前的线程情况。
假设run方法中有多条指令在执行。
如果通过stop强制终止,那么可能会导致数据不完整,所以不建议这样使用。
那如何解决呢?
线程中断
可以通过interrupt 来做。但是interrupt不是用来终止的方法,而是发送一个信号,需要对其进行额外处理才可以起到终止的效果。
public class InterruptDemo implements Runnable{private int i=0;@Overridepublic void run() {//isInterrupted 默认falsewhile(!Thread.currentThread().isInterrupted()){System.out.println("this is Thread : "+ (i++) +" - " +Thread.currentThread().getName());}}public static void main(String[] args) throws InterruptedException {Thread t = new Thread(new InterruptDemo());t.start();Thread.sleep(1000);//主线程timed_waiting 1秒t.interrupt();//设置 interrupted=true}
}
执行结果:
......
this is Thread : 69 - Thread-0
this is Thread : 70 - Thread-0
this is Thread : 71 - Thread-0Process finished with exit code 0
当我们的run
方法中,如果存在一个无法终止的操作时(比如while(true)
、比如sleep(200000)
)
它们会使线程阻塞,无法运行,也无法终止,这时要考虑使用interrupt 来中断。
线程复位
在Java线程中,针对阻塞的操作,如果想去唤醒它,它会提供一个中断的异常抛出。
但凡是让线程阻塞的机制(方法),都会抛出中断异常(InterruptedException
),需要去处理。
import java.util.concurrent.TimeUnit;public class InterruptExceptionDemo implements Runnable{@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()){try {TimeUnit.SECONDS.sleep(200);} catch (InterruptedException e) {//触发了线程复位 isInterrupted-> falsee.printStackTrace();}}System.out.println("thread is end.");}public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(new InterruptExceptionDemo());thread.start();Thread.sleep(1000);thread.interrupt();}
}
控台打印结果:
我们中thread.interrupt() 后,run方法响应来异常,进入catch代码块。
由于触发了线程复位,所以isInterrupted 又重置为 false。
我们需要中catch块中对中断做出处理,可以有的处理方式:
- 如果不做处理,那么由于中断复位会使线程继续处于sleep状态。
- 继续中断,将选择权给到run方法,Thread.currentThread().interrupt(); //再次中断
- 抛出异常。
复位是JVM层面做的,它会在抛异常之前,设置状态为false,即复位。
为什么复位,因为我们处理当前线程的权限应该由线程本身来控制,如果不复位的话,下次循环就会终止,就相当于线程的终止由线程外部来控制了。
线程终止的本质
public void interrupt() {if (this != Thread.currentThread())checkAccess();synchronized (blockerLock) {Interruptible b = blocker;if (b != null) {interrupt0(); // Just to set the interrupt flagb.interrupt(this);return;}}interrupt0();}private native void interrupt0();
我们可以看到,Thread的interrupt
方法,最终是调动了一个native的interrupt0
方法。
而在JVM中,我们可以看到 interrupt0 做了什么。
我们先来看JVM的 jvm.cpp:
JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))JVMWrapper("JVM_Interrupt");// Ensure that the C++ Thread and OSThread structures aren't freed before we operateoop java_thread = JNIHandles::resolve_non_null(jthread);MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);// We need to re-resolve the java_thread, since a GC might have happened during the// acquire of the lockJavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));if (thr != NULL) {Thread::interrupt(thr);}
JVM_END
其中最后的 Thread::interrupt(thr) 调用了操作系统层面的中断。
我们找到linux对应的os_linux.cpp
文件:
进入文件找到interrupt方法如下:
// interrupt supportvoid os::interrupt(Thread* thread) {assert(Thread::current() == thread || Threads_lock->owned_by_self(),"possibility of dangling Thread pointer");OSThread* osthread = thread->osthread();if (!osthread->interrupted()) {osthread->set_interrupted(true);//设置一个中断状态// More than one thread can get here with the same value of osthread,// resulting in multiple notifications. We do, however, want the store// to interrupted() to be visible to other threads before we execute unpark().OrderAccess::fence();ParkEvent * const slp = thread->_SleepEvent ;//如果是sleep中,唤醒if (slp != NULL) slp->unpark() ;}// For JSR166. Unpark even if interrupt status already was setif (thread->is_Java_thread())((JavaThread*)thread)->parker()->unpark();ParkEvent * ev = thread->_ParkEvent ;if (ev != NULL) ev->unpark() ;}
上面代码是os的interrupt逻辑,会发现,它不仅仅是设置来一个interrupted变量值,
而且还有 upark的唤醒逻辑。
interrupt()
- 设置一个共享变量的值 true
- 唤醒处于阻塞状态下的线程
相关文章:

如何终止一个线程
如何终止一个线程 是使用 thread.stop() 吗? public class ThreadDemo extends Thread{Overridepublic void run() {try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("this is demo thread :"Thre…...

上岸!选择你的隐私计算导师!
开放隐私计算 开放隐私计算开放隐私计算OpenMPC是国内第一个且影响力最大的隐私计算开放社区。社区秉承开放共享的精神,专注于隐私计算行业的研究与布道。社区致力于隐私计算技术的传播,愿成为中国 “隐私计算最后一公里的服务区”。183篇原创内容公众号…...

go gin学习记录5
有了前面几节的学习,如果做个简单的web服务端已经可以完成了。 这节来做一下优化。 我们实验了3种SQL写入的方法,但是发现每一种都需要在方法中去做数据库链接的操作,有些重复了。 所以,我们把这部分提取出来,数据库链…...

PyQt5数据库开发2 5.1 QSqlQueryModel
目录 一、Qt窗体设计 1. 新建Qt项目 2. 拷贝4-3的部分组件过来 3. 添加资源文件 4. 创建Action 5. 添加工具栏 6. 创建菜单项 7. 关闭Action的实现 8. 调整布局 8.1 调整两个groupbox的布局 8.3 为窗体设置全局布局 二、代码拷贝和删除 1. 新建项目目录 2. 编译…...

MySQL-redo log和undo log
什么是事务 事务是由数据库中一系列的访问和更新组成的逻辑执行单元 事务的逻辑单元中可以是一条SQL语句,也可以是一段SQL逻辑,这段逻辑要么全部执行成功,要么全部执行失败 举个最常见的例子,你早上出去买早餐,支付…...

阿里云ECS TOP性能提升超20%!KeenTune助力倚天+Alinux3达成开机即用的全栈性能调优 | 龙蜥技术
文/KeenTune SIG01阿里云 ECS 上售卖页新增“应用加速”功能2023年1月12日 阿里云 ECS 的售卖页有了一些新的变化,在用户选择倚天 Alinux3 新建实例时,多了一个新的选项“应用加速”。这个功能是 阿里云 ECS 基于 KeenTune 提供典型云场景的开机即用的全…...
华为OD机试真题Python实现【快递业务站】真题+解题思路+代码(20222023)
快递业务站 题目 快递业务范围有 N 个站点,A 站点与 B 站点可以中转快递,则认为 A-B 站可达, 如果 A-B 可达,B-C 可达,则 A-C 可达。 现在给 N 个站点编号 0、1、…n-1,用 s[i][j]表示 i-j 是否可达, s[i][j] = 1表示 i-j可达,s[i][j] = 0表示 i-j 不可达。 现用二维…...

【c语言】预处理
🚀write in front🚀 📜所属专栏:> c语言学习 🛰️博客主页:睿睿的博客主页 🛰️代码仓库:🎉VS2022_C语言仓库 🎡您的点赞、关注、收藏、评论,是…...

嵌入式常用知识
12、并发和并行的区别? 最本质的区别就是:并发是轮流处理多个任务,并行是同时处理多个任务。 你吃饭吃到一半,电话来了,你一直到吃完了以后才去接,这就说明你不支持并发也不支持并行。 你吃饭吃到一半&…...

和平精英五曜赐福返场,老款玛莎返场来了
和平精英五曜赐福返场,老款玛莎返场来了!新款如何选择! 关于返场的新消息,都说云南百收SEO解说消息不准,之前看过文章的应该会知道,全网只有云南百收SEO解说发了。玛莎返场,快喊你的阿姨来看&a…...

React从入门到精通二
React从入门到精通之购物车案例1. 购物车需求说明使用到的data list2. 项目code1. 购物车需求说明 list data展示到列表中每个item的通过按钮来控制购买的数据量删除按钮可以删除当前的itemTotal Price计算当前购物车的总的价格 使用到的data list const books [{id: 1,name…...

【likeshop多商户】电子面单商家直播上线啦~
likeshop多商户商城v2.2.0版本更新啦! 新增功能: 商家直播 单子面单 优化: 个人中心优惠券数量统计优化 修复: 秒杀商品待审核时,下单价格计算错误 个人中心修改头像后地址保存错误 「商家直播」 提升品牌知名度…...

游戏化销售管理是什么?使用CRM系统进行有什么用?
对于企业销售来说,高薪酬也伴随着更高的压力与挑战。高强度的单一工作会让销售人员逐渐失去对工作的兴趣,导致销售状态缺少动力和激情,工作开展愈加困难。您可以通过CRM系统进行游戏化销售管理,让销售人员重新干劲满满。 游戏并不…...

Mysql 索引(三)—— 不同索引的创建方式(主键索引、普通索引、唯一键索引)
了解了主键索引的底层原理,主键索引其实就是根据主键字段建立相关的数据结构(B树),此后在使用主键字段作为条件查询时,会直接根据主键查找B树的叶子结点。除了主键索引外,普通索引和唯一键索引也是如此&…...

秒懂算法 | 基于朴素贝叶斯算法的垃圾信息的识别
本文将带领大家亲手实现一个垃圾信息过滤的算法。 在正式讲解算法之前,最重要的是对整个任务有一个全面的认识,包括算法的输入和输出、可能会用到的技术,以及技术大致的流程。 本任务的目标是去识别一条短信是否为垃圾信息,即输入为一条文本信息,输出为二分类的分类结果。…...

SpringCloud - Feign远程调用
目录 Feign的远程调用 RestTemplate方式调用存在的问题 介绍与初步使用 Feign的自定义配置 Feign运行自定义配置来覆盖默认配置,可以修改的配置如下: 配置Feign日志有两种方式: Feign性能优化 Feign底层的客户端实现: 连…...

Eotalk Vol.03:结合 API DaaS,让使用数据更方便
Eotalk 是由 Eolink CEO 刘昊臻发起的泛技术聊天活动,每期都会邀请一些技术圈内的大牛聊聊天,聊些关于技术、创业工作、投融资等热点话题。 Eotalk 的第 3 期,很高兴邀请到 Tapdata CEO TJ 唐建法,TJ 可以说是一位超级大咖&#x…...
从零开始学习Java编程:一份详细指南
Java入门Java简介和历史Java开发环境的安装和配置Java开发工具的介绍和使用(例如Eclipse、IntelliJ IDEA等)Java语言的基本概念(例如变量、数据类型、运算符、流程控制语句等)面向对象编程基础面向对象编程概念和基本原则类和对象…...

电子技术——系统性分析反馈电压放大器
电子技术——系统性分析反馈电压放大器 在本节我们提供一个系统性的分析反馈电压放大器的方法。首先我们考虑反馈网络没有负载效应理想情况,其次我们考虑反馈网络有限阻抗下的非理想情况。总之,这种方法的思路在于,将非理想情况转换为理想情况…...

【C语言进阶】结构体、位段、枚举、以及联合(共用体)的相关原理与使用
📝个人主页:Sherry的成长之路 🏠学习社区:Sherry的成长之路(个人社区) 📖专栏链接:C语言进阶 🎯长路漫漫浩浩,万事皆有期待 文章目录1.结构体1.1 概述&a…...
2024年赣州旅游投资集团社会招聘笔试真
2024年赣州旅游投资集团社会招聘笔试真 题 ( 满 分 1 0 0 分 时 间 1 2 0 分 钟 ) 一、单选题(每题只有一个正确答案,答错、不答或多答均不得分) 1.纪要的特点不包括()。 A.概括重点 B.指导传达 C. 客观纪实 D.有言必录 【答案】: D 2.1864年,()预言了电磁波的存在,并指出…...
【论文笔记】若干矿井粉尘检测算法概述
总的来说,传统机器学习、传统机器学习与深度学习的结合、LSTM等算法所需要的数据集来源于矿井传感器测量的粉尘浓度,通过建立回归模型来预测未来矿井的粉尘浓度。传统机器学习算法性能易受数据中极端值的影响。YOLO等计算机视觉算法所需要的数据集来源于…...
【算法训练营Day07】字符串part1
文章目录 反转字符串反转字符串II替换数字 反转字符串 题目链接:344. 反转字符串 双指针法,两个指针的元素直接调转即可 class Solution {public void reverseString(char[] s) {int head 0;int end s.length - 1;while(head < end) {char temp …...

12.找到字符串中所有字母异位词
🧠 题目解析 题目描述: 给定两个字符串 s 和 p,找出 s 中所有 p 的字母异位词的起始索引。 返回的答案以数组形式表示。 字母异位词定义: 若两个字符串包含的字符种类和出现次数完全相同,顺序无所谓,则互为…...
Unit 1 深度强化学习简介
Deep RL Course ——Unit 1 Introduction 从理论和实践层面深入学习深度强化学习。学会使用知名的深度强化学习库,例如 Stable Baselines3、RL Baselines3 Zoo、Sample Factory 和 CleanRL。在独特的环境中训练智能体,比如 SnowballFight、Huggy the Do…...

华为云Flexus+DeepSeek征文|DeepSeek-V3/R1 商用服务开通全流程与本地部署搭建
华为云FlexusDeepSeek征文|DeepSeek-V3/R1 商用服务开通全流程与本地部署搭建 前言 如今大模型其性能出色,华为云 ModelArts Studio_MaaS大模型即服务平台华为云内置了大模型,能助力我们轻松驾驭 DeepSeek-V3/R1,本文中将分享如何…...
CMake控制VS2022项目文件分组
我们可以通过 CMake 控制源文件的组织结构,使它们在 VS 解决方案资源管理器中以“组”(Filter)的形式进行分类展示。 🎯 目标 通过 CMake 脚本将 .cpp、.h 等源文件分组显示在 Visual Studio 2022 的解决方案资源管理器中。 ✅ 支持的方法汇总(共4种) 方法描述是否推荐…...

AI书签管理工具开发全记录(十九):嵌入资源处理
1.前言 📝 在上一篇文章中,我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源,方便后续将资源打包到一个可执行文件中。 2.embed介绍 🎯 Go 1.16 引入了革命性的 embed 包,彻底改变了静态资源管理的…...
DeepSeek 技术赋能无人农场协同作业:用 AI 重构农田管理 “神经网”
目录 一、引言二、DeepSeek 技术大揭秘2.1 核心架构解析2.2 关键技术剖析 三、智能农业无人农场协同作业现状3.1 发展现状概述3.2 协同作业模式介绍 四、DeepSeek 的 “农场奇妙游”4.1 数据处理与分析4.2 作物生长监测与预测4.3 病虫害防治4.4 农机协同作业调度 五、实际案例大…...
【前端异常】JavaScript错误处理:分析 Uncaught (in promise) error
在前端开发中,JavaScript 异常是不可避免的。随着现代前端应用越来越多地使用异步操作(如 Promise、async/await 等),开发者常常会遇到 Uncaught (in promise) error 错误。这个错误是由于未正确处理 Promise 的拒绝(r…...