腾讯面试官:如何停止一个正在运行的线程?我蒙了。。。

2024-09-02 08:48

本文主要是介绍腾讯面试官:如何停止一个正在运行的线程?我蒙了。。。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

点击上方“朱小厮的博客”,选择“设为星标”

后台回复"书",获取

后台回复“k8s”,可领取k8s资料

停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用Thread.stop()方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。在java中有以下3种方法可以终止正在运行的线程:

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。

  2. 使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。

  3. 使用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=500000

2. 判断线程是否停止状态

Thread.java类中提供了两种方法:

  1. this.interrupted(): 测试当前线程是否已经中断;

  2. 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.InterruptedExceptionat 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 interruptedat 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 interruptedat 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=9Process finished with exit code 0

6.方法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块中还可以将异常向上抛,使线程停止事件得以传播。

来源:cnblogs.com/greta/p/5624839.html

想知道更多?描下面的二维码关注我

后台回复"技术",加入技术群

后台回复“k8s”,可领取k8s资料

【精彩推荐】

  • ClickHouse到底是什么?为什么如此牛逼!

  • 原来ElasticSearch还可以这么理解

  • 面试官:InnoDB中一棵B+树可以存放多少行数据?

  • 架构之道:分离业务逻辑和技术细节

  • 星巴克不使用两阶段提交

  • 面试官:Redis新版本开始引入多线程,谈谈你的看法?

  • 喜马拉雅自研网关架构演进过程

  • 收藏:存储知识全面总结

  • 微博千万级规模高性能高并发的网络架构设计

这篇关于腾讯面试官:如何停止一个正在运行的线程?我蒙了。。。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1129522

相关文章

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

java父子线程之间实现共享传递数据

《java父子线程之间实现共享传递数据》本文介绍了Java中父子线程间共享传递数据的几种方法,包括ThreadLocal变量、并发集合和内存队列或消息队列,并提醒注意并发安全问题... 目录通过 ThreadLocal 变量共享数据通过并发集合共享数据通过内存队列或消息队列共享数据注意并发安全问题总结在 J

通过prometheus监控Tomcat运行状态的操作流程

《通过prometheus监控Tomcat运行状态的操作流程》文章介绍了如何安装和配置Tomcat,并使用Prometheus和TomcatExporter来监控Tomcat的运行状态,文章详细讲解了... 目录Tomcat安装配置以及prometheus监控Tomcat一. 安装并配置tomcat1、安装

异步线程traceId如何实现传递

《异步线程traceId如何实现传递》文章介绍了如何在异步请求中传递traceId,通过重写ThreadPoolTaskExecutor的方法和实现TaskDecorator接口来增强线程池,确保异步... 目录前言重写ThreadPoolTaskExecutor中方法线程池增强总结前言在日常问题排查中,

mysqld_multi在Linux服务器上运行多个MySQL实例

《mysqld_multi在Linux服务器上运行多个MySQL实例》在Linux系统上使用mysqld_multi来启动和管理多个MySQL实例是一种常见的做法,这种方式允许你在同一台机器上运行多个... 目录1. 安装mysql2. 配置文件示例配置文件3. 创建数据目录4. 启动和管理实例启动所有实例

IDEA运行spring项目时,控制台未出现的解决方案

《IDEA运行spring项目时,控制台未出现的解决方案》文章总结了在使用IDEA运行代码时,控制台未出现的问题和解决方案,问题可能是由于点击图标或重启IDEA后控制台仍未显示,解决方案提供了解决方法... 目录问题分析解决方案总结问题js使用IDEA,点击运行按钮,运行结束,但控制台未出现http://

解决Spring运行时报错:Consider defining a bean of type ‘xxx.xxx.xxx.Xxx‘ in your configuration

《解决Spring运行时报错:Considerdefiningabeanoftype‘xxx.xxx.xxx.Xxx‘inyourconfiguration》该文章主要讲述了在使用S... 目录问题分析解决方案总结问题Description:Parameter 0 of constructor in x

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

Linux使用nohup命令在后台运行脚本

《Linux使用nohup命令在后台运行脚本》在Linux或类Unix系统中,后台运行脚本是一项非常实用的技能,尤其适用于需要长时间运行的任务或服务,本文我们来看看如何使用nohup命令在后台... 目录nohup 命令简介基本用法输出重定向& 符号的作用后台进程的特点注意事项实际应用场景长时间运行的任务服