腾讯面试官如何停止一个正在运行的线程?我一脸懵逼
目录1. 停止不了的线程 2. 判断线程是否停止状态 3. 能停止的线程--异常法 4. 在沉睡中停止 5. 能停止的线程---暴力停止 6.方法stop()与java.lang.ThreadDeath异常 7. 释放锁的不良后果 8. 使用return停止线程
停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用Thread.stop()方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。在java中有以下3种方法可以终止正在运行的线程: 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。 使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。 使用interrupt方法中断线程。 1. 停止不了的线程
interrupt()方法的使用效果并不像for+break语句那样,马上就停止循环。调用interrupt方法是在当前线程中打了一个停止标志,并不是真的停止线程。 public class MyThread extends Thread { public void run(){ super.run(); for(int i=0; i<500000; i++){ System.out.println("i="+(i+1)); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); thread.start(); try { Thread.sleep(2000); thread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }
输出结果: ... i=499994 i=499995 i=499996 i=499997 i=499998 i=499999 i=5000002. 判断线程是否停止状态
Thread.java类中提供了两种方法: this.interrupted(): 测试当前线程是否已经中断; this.isInterrupted(): 测试线程是否已经中断;
那么这两个方法有什么图区别呢?我们先来看看this.interrupted()方法的解释:测试当前线程是否已经中断,当前线程是指运行this.interrupted()方法的线程。 public class MyThread extends Thread { public void run(){ super.run(); for(int i=0; i<500000; i++){ i++; // System.out.println("i="+(i+1)); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); thread.start(); try { Thread.sleep(2000); thread.interrupt(); System.out.println("stop 1??" + thread.interrupted()); System.out.println("stop 2??" + thread.interrupted()); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果: stop 1??false stop 2??false
类Run.java中虽然是在thread对象上调用以下代码:thread.interrupt(), 后面又使用 System.out.println("stop 1??" + thread.interrupted()); System.out.println("stop 2??" + thread.interrupted());
来判断thread对象所代表的线程是否停止,但从控制台打印的结果来看,线程并未停止,这也证明了interrupted()方法的解释,测试当前线程是否已经中断。这个当前线程是main,它从未中断过,所以打印的结果是两个false.
如何使main线程产生中断效果呢? public class Run2 { public static void main(String args[]){ Thread.currentThread().interrupt(); System.out.println("stop 1??" + Thread.interrupted()); System.out.println("stop 2??" + Thread.interrupted()); System.out.println("End"); } }
运行效果为: stop 1??true stop 2??false End
方法interrupted()的确判断出当前线程是否是停止状态。但为什么第2个布尔值是false呢?官方帮助文档中对interrupted方法的解释: 测试当前线程是否已经中断。线程的中断状态由该方法清除。 换句话说,如果连续两次调用该方法,则第二次调用返回false。
下面来看一下inInterrupted()方法。 public class Run3 { public static void main(String args[]){ Thread thread = new MyThread(); thread.start(); thread.interrupt(); System.out.println("stop 1??" + thread.isInterrupted()); System.out.println("stop 2??" + thread.isInterrupted()); } }
运行结果: stop 1??true stop 2??true
isInterrupted()并未清除状态,所以打印了两个true。 3. 能停止的线程--异常法
有了前面学习过的知识点,就可以在线程中用for语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可: public class MyThread extends Thread { public void run(){ super.run(); for(int i=0; i<500000; i++){ if(this.interrupted()) { System.out.println("线程已经终止, for循环不再执行"); break; } System.out.println("i="+(i+1)); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); thread.start(); try { Thread.sleep(2000); thread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果: ... i=202053 i=202054 i=202055 i=202056 线程已经终止, for循环不再执行
上面的示例虽然停止了线程,但如果for语句下面还有语句,还是会继续运行的。看下面的例子: public class MyThread extends Thread { public void run(){ super.run(); for(int i=0; i<500000; i++){ if(this.interrupted()) { System.out.println("线程已经终止, for循环不再执行"); break; } System.out.println("i="+(i+1)); } System.out.println("这是for循环外面的语句,也会被执行"); } }
使用Run.java执行的结果是: ... i=180136 i=180137 i=180138 i=180139 线程已经终止, for循环不再执行 这是for循环外面的语句,也会被执行
如何解决语句继续运行的问题呢?看一下更新后的代码: public class MyThread extends Thread { public void run(){ super.run(); try { for(int i=0; i<500000; i++){ if(this.interrupted()) { System.out.println("线程已经终止, for循环不再执行"); throw new InterruptedException(); } System.out.println("i="+(i+1)); } System.out.println("这是for循环外面的语句,也会被执行"); } catch (InterruptedException e) { System.out.println("进入MyThread.java类中的catch了…"); e.printStackTrace(); } } }
使用Run.java运行的结果如下: ... i=203798 i=203799 i=203800 线程已经终止, for循环不再执行 进入MyThread.java类中的catch了… java.lang.InterruptedException at thread.MyThread.run(MyThread.java:13)4. 在沉睡中停止
如果线程在sleep()状态下停止线程,会是什么效果呢? public class MyThread extends Thread { public void run(){ super.run(); try { System.out.println("线程开始…"); Thread.sleep(200000); System.out.println("线程结束。"); } catch (InterruptedException e) { System.out.println("在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:" + this.isInterrupted()); e.printStackTrace(); } } }
使用Run.java运行的结果是: 线程开始… 在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:false java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at thread.MyThread.run(MyThread.java:12)
从打印的结果来看, 如果在sleep状态下停止某一线程,会进入catch语句,并且清除停止状态值,使之变为false。
前一个实验是先sleep然后再用interrupt()停止,与之相反的操作在学习过程中也要注意: public class MyThread extends Thread { public void run(){ super.run(); try { System.out.println("线程开始…"); for(int i=0; i<10000; i++){ System.out.println("i=" + i); } Thread.sleep(200000); System.out.println("线程结束。"); } catch (InterruptedException e) { System.out.println("先停止,再遇到sleep,进入catch异常"); e.printStackTrace(); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); thread.start(); thread.interrupt(); } }
运行结果: i=9998 i=9999 先停止,再遇到sleep,进入catch异常 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at thread.MyThread.run(MyThread.java:15)5. 能停止的线程---暴力停止
使用stop()方法停止线程则是非常暴力的。 public class MyThread extends Thread { private int i = 0; public void run(){ super.run(); try { while (true){ System.out.println("i=" + i); i++; Thread.sleep(200); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Run { public static void main(String args[]) throws InterruptedException { Thread thread = new MyThread(); thread.start(); Thread.sleep(2000); thread.stop(); } }
运行结果: i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 Process finished with exit code 06.方法stop()与java.lang.ThreadDeath异常
调用stop()方法时会抛出java.lang.ThreadDeath异常,但是通常情况下,此异常不需要显示地捕捉。 public class MyThread extends Thread { private int i = 0; public void run(){ super.run(); try { this.stop(); } catch (ThreadDeath e) { System.out.println("进入异常catch"); e.printStackTrace(); } } } public class Run { public static void main(String args[]) throws InterruptedException { Thread thread = new MyThread(); thread.start(); } }
stop()方法以及作废,因为如果强制让线程停止有可能使一些清理性的工作得不到完成。另外一个情况就是对锁定的对象进行了解锁,导致数据得不到同步的处理,出现数据不一致的问题。 7. 释放锁的不良后果
使用stop()释放锁将会给数据造成不一致性的结果。如果出现这样的情况,程序处理的数据就有可能遭到破坏,最终导致程序执行的流程错误,一定要特别注意: public class SynchronizedObject { private String name = "a"; private String password = "aa"; public synchronized void printString(String name, String password){ try { this.name = name; Thread.sleep(100000); this.password = password; } catch (InterruptedException e) { e.printStackTrace(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public class MyThread extends Thread { private SynchronizedObject synchronizedObject; public MyThread(SynchronizedObject synchronizedObject){ this.synchronizedObject = synchronizedObject; } public void run(){ synchronizedObject.printString("b", "bb"); } } public class Run { public static void main(String args[]) throws InterruptedException { SynchronizedObject synchronizedObject = new SynchronizedObject(); Thread thread = new MyThread(synchronizedObject); thread.start(); Thread.sleep(500); thread.stop(); System.out.println(synchronizedObject.getName() + " " + synchronizedObject.getPassword()); } }
输出结果: b aa
由于stop()方法以及在JDK中被标明为"过期/作废"的方法,显然它在功能上具有缺陷,所以不建议在程序张使用stop()方法。 8. 使用return停止线程
将方法interrupt()与return结合使用也能实现停止线程的效果: public class MyThread extends Thread { public void run(){ while (true){ if(this.isInterrupted()){ System.out.println("线程被停止了!"); return; } System.out.println("Time: " + System.currentTimeMillis()); } } } public class Run { public static void main(String args[]) throws InterruptedException { Thread thread = new MyThread(); thread.start(); Thread.sleep(2000); thread.interrupt(); } }
输出结果: ... Time: 1467072288503 Time: 1467072288503 Time: 1467072288503 线程被停止了!
不过还是建议使用"抛异常"的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止事件得以传播。 最后
在这里我再分享一份由多位大佬亲自收录整理的Android学习PDF+架构视频+面试文档+源码笔记,高级架构技术进阶脑图、Android开发面试专题资料,高级进阶架构资料
这些都是我现在闲暇时还会反复翻阅的精品资料。里面对近几年的大厂面试高频知识点都有详细的讲解。相信可以有效地帮助大家掌握知识、理解原理,帮助大家在未来面试取得一份不错的答卷。
当然,你也可以拿去查漏补缺,提升自身的竞争力。
如果你有需要的话,只需私信我【进阶】即可获取
比亚迪海洋车系正式发8月13日,比亚迪海洋车系正式发布。作为该车系的首款车型,比亚迪海豚的预售同步开启,共四款车型,预售价格区间为9。68万元12。48万元,预售期下订的用户可以获得海豚领YOUNG计
adolbook132021迷幻海洋大学生最值得入手高颜值轻薄本对大学生而言,高颜值是他们挑选电子产品的一个重要筛选条件,但性能与实用性同样不可或缺。所以,有实力体现的前提又有高颜值傍身,无疑是锦上添花。毕业季后,大学生最值得入手的高颜值轻薄本
海洋守护之旅,ATFX积极参与海洋生态修复和珊瑚再生ATFX动态菲律宾最主要的旅游景点之一潘格劳岛(Panglao),多年来都是全球旅游爱好者和潜水的天堂,每年吸引数以百万计的游客到这里游玩,从而促进了岛上的商业发展和就业机会的增加
蜂网舞阳专家电话会议第十三期海上风电并网冲刺,风电王者归来?今年是海上风电并网补贴的最后一年,双碳大背景之下,海上风电迎来一波抢装潮,相关上市公司海风业务快速增长。多位业内人士表示,在政策推动和技术越发成熟因素影响下,海上风电2023年将进
海上风电热潮激发海底电缆需求上市公司开足马力抢份额财联社(青岛,记者肖良华)讯,在碳中和碳达峰目标推动下,海上风电迎来超预期发展,带动包括海底电缆(以下简称海缆)在内的相关产业链不断升级。汉缆股份(002498。SZ)董秘王正庄在
开源项目EasyDarwin为什么如此受开发者欢迎?早期的创造者基于开源技术构建了互联网本身的大部分比如Linux操作系统和ApacheWeb服务器应用任何今天使用互联网的人都受益于开源项目。大家了解TSINGSEE应该都是从Eas
公共安防酒店的安全监控为何如此重要?一背景介绍酒店宾馆等场所出入人员比较繁多,外地客人又占绝大部分,而犯罪分子恰好利用这种环境,潜入酒店宾馆伺机作案,直接影响到客人的人身安全和财产安全,直接影响到酒店宾馆的声誉。为进
程序员必看13个GitHub开源又炫酷的计算机视觉项目在这篇文章中,我们列出了一些令人敬畏的计算机视觉GitHub库,希望这些库能激励所有的AI开发者们像这样去构建自己的项目。计算机视觉GitHub知识库1使用CNN进行三维人脸重建(
免费升级Window11,只需十分钟Windows11预览版已正式开始推送,目前在售的大部分Windows10电脑都能免费升级到Windows11啦!你,准备好了吗?如何升级Windows11目前微软官方推出的Win
无畏15好屏好价,这才是我要的高能轻薄本说到今年排得上号的高能轻薄本,华硕无畏系列必定入榜。无畏系列在上半年连推出了两台实力轻薄本,个顶个的能打,其中无畏15更是在618大促中突出重围,在一众优秀的轻薄本中获得了较高的反
微信的这个新功能,比彩铃更好用近日,微信推出了一波让人欣喜的新功能。更改消息提示音设置来电铃声折叠置顶聊天缩小语音来电页面(不再全屏),等等等等你最喜欢哪一个?01。hr彩铃依次点击我设置新消息通知来电铃声更换
金秋九月SUV销量前五分析,奇骏逍客竟双双落马金九银十,在中秋节和70周年国庆热点的消费环境刺激下,9月份SUV整体销量获得小幅提升。据乘联会数据消息,我国9月份SUV车型总销量为80。88万辆,环比增长14。5,但累计销量同
保时捷卡宴新增SCoup车型,搭载2。9T发动机破百只需5秒近期,保时捷公布了Cayenne系列新增车型CayenneSCoup,新增车型官方指导售价为123。60万元。外观方面,CayenneSCoup与早些发布的CayenneCoup在
买菜车雅力士将全方位升级,飞度表示有压力近日,丰田发布了2020款雅力士的渲染图。据悉,全新的丰田雅力士基于TNGAB平台设计打造,使其车身的整体高度降低了40mm,导致座位比较低矮且更接近方向盘,以TNGAB平台为基础
BBA之外的好选择,降价超过4万的凯迪拉克XT5谈及豪华品牌的中型SUV,德系三驾马车无疑是第一梯队的,宝马X3奔驰GLCL和奥迪Q5L都是过万的超热门车型。第二梯队中凯迪拉克XT5英菲尼迪QX50林肯MKC紧随其后。这次给大家
越强硬越好开,试一台特别的领克03如果说到近期汽车圈里最热门是什么车型?那必定是领克03无疑。凭借着在WTCR宁波站一举夺魁的优异表现,很多人对这款冠军车产生了莫大的兴趣。但要知道一台WTCR赛车与量产车之间存在着
新款宝马5系已于近期到店,改动不大2020款宝马5系车型已于前段时间上市,虽然是更新为新款车型,但此次宝马5系仅为中期改款,并未像其小弟三系和大哥七系那样采用全新的设计语言,2020款宝马5系外观依旧与19款保持一
远看雷克萨斯,近看丰田,致炫跨界新选择据了解全新YARiSL致炫X于10月21日上市,该车共推出了八个车型,售价区间为7。78万10。38万元。全系配置了一台1。5L自然吸气发动机,传动方面分别为5挡MT变速器和CVT
上市两年都没什么优惠,小改款后配置动力升级,推荐购买2。0G试车报告中级车一直都是国内消费者的购车首选,不仅车型多,而且价格也持续下探,现在不少中级车都在20万以内性价比突出。如果要你选一款中级车,20万左右空间充足配置适中还要省油耐用,相
自动洗箱机的正确操作事项自动洗箱机多用于一些农业食品加工厂和零部件制造行业清洗一些塑料盒,但洗衣机和人一样,长时间工作后会很累,需要保养。所以全自动洗衣机的操作非常重要。如果你不小心,就会降低效率。那么在
商用洗碗机的正确操作常识选择商用洗碗机并正确使用,不仅可以节约用水和洗涤剂,而且可以有效地洗碗,改善就餐环境和整体卫生。正确使用商用洗碗机的常识是什么?如何使餐具清洗更干净?1。餐具使用后应尽快清洗干净。
商用洗碗机正确操作的常识选择商用洗碗机并正确使用,不仅可以节约用水和洗涤剂,而且可以有效地洗碗,改善就餐环境和整体卫生。正确使用商用洗碗机的常识是什么?如何使餐具洗得更干净?1。餐具使用后应尽快清洗干净,