【Java并发编程】:线程中断
使用interrupt()中断线程
当一个线程运行时,另一个线程可以调用对应的Thread对象的interrupt()方法来中断它,该方法只是在目标线程中设置一个标志,表示它已经被中断,并立即返回。这里需要注意的是,如果只是单纯的调用interrupt()方法,线程并没有实际被中断,会继续往下执行。
下面一段代码演示了休眠线程的中断:
- public class SleepInterrupt extends Object implements Runnable{
- public void run(){
- try{
- System.out.println("in run() - about to sleep for 20 seconds");
- Thread.sleep(20000);
- System.out.println("in run() - woke up");
- }catch(InterruptedException e){
- System.out.println("in run() - interrupted while sleeping");
- //处理完中断异常后,返回到run()方法人口,
- //如果没有return,线程不会实际被中断,它会继续打印下面的信息
- return;
- }
- System.out.println("in run() - leaving normally");
- }
- public static void main(String[] args) {
- SleepInterrupt si = new SleepInterrupt();
- Thread t = new Thread(si);
- t.start();
- //主线程休眠2秒,从而确保刚才启动的线程有机会执行一段时间
- try {
- Thread.sleep(2000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println("in main() - interrupting other thread");
- //中断线程t
- t.interrupt();
- System.out.println("in main() - leaving");
- }
- }
运行结果如下:
to sleep for 20
seconds”后,继而休眠20秒钟,大约2秒钟后,main线程通知新线程中断,那么新线程的20秒的休眠将被打断,从而抛出InterruptException异常,执行跳转到catch块,打印出“interrupted
while sleeping”信息,并立即从run()方法返回,然后消亡,而不会打印出catch块后面的“leaving
normally”信息。
待决中断
在上面的例子中,sleep()方法的实现检查到休眠线程被中断,它会相当友好地终止线程,并抛出InterruptedException异常。另外一种情况,如果线程在调用sleep()方法前被中断,那么该中断称为待决中断,它会在刚调用sleep()方法时,立即抛出InterruptedException异常。
下面的代码演示了待决中断:
- public class PendingInterrupt extends Object {
- public static void main(String[] args){
- //如果输入了参数,则在mian线程中中断当前线程(亦即main线程)
- if( args.length > 0 ){
- Thread.currentThread().interrupt();
- }
- //获取当前时间
- long startTime = System.currentTimeMillis();
- try{
- Thread.sleep(2000);
- System.out.println("was NOT interrupted");
- }catch(InterruptedException x){
- System.out.println("was interrupted");
- }
- //计算中间代码执行的时间
- System.out.println("elapsedTime=" + ( System.currentTimeMillis() - startTime));
- }
- }
如果PendingInterrupt不带任何命令行参数,那么线程不会被中断,最终输出的时间差距应该在2000附近(具体时间由系统决定,不精确),如果PendingInterrupt带有命令行参数,则调用中断当前线程的代码,但main线程仍然运行,最终输出的时间差距应该远小于2000,因为线程尚未休眠,便被中断,因此,一旦调用sleep()方法,会立即打印出catch块中的信息。执行结果如下:
这种模式下,main线程中断它自身。除了将中断标志(它是Thread的内部标志)设置为true外,没有其他任何影响。线程被中断了,但main线程仍然运行,main线程继续监视实时时钟,并进入try块,一旦调用sleep()方法,它就会注意到待决中断的存在,并抛出InterruptException。于是执行跳转到catch块,并打印出线程被中断的信息。最后,计算并打印出时间差。
使用isInterrupted()方法判断中断状态
- public class InterruptCheck extends Object{
- public static void main(String[] args){
- Thread t = Thread.currentThread();
- System.out.println("Point A: t.isInterrupted()=" + t.isInterrupted());
- //待决中断,中断自身
- t.interrupt();
- System.out.println("Point B: t.isInterrupted()=" + t.isInterrupted());
- System.out.println("Point C: t.isInterrupted()=" + t.isInterrupted());
- try{
- Thread.sleep(2000);
- System.out.println("was NOT interrupted");
- }catch( InterruptedException x){
- System.out.println("was interrupted");
- }
- //抛出异常后,会清除中断标志,这里会返回false
- System.out.println("Point D: t.isInterrupted()=" + t.isInterrupted());
- }
- }
运行结果如下:
使用Thread.interrupted()方法判断中断状态
可以使用Thread.interrupted()方法来检查当前线程的中断状态(并隐式重置为false)。又由于它是静态方法,因此不能在特定的线程上使用,而只能报告调用它的线程的中断状态,如果线程被中断,而且中断状态尚不清楚,那么,这个方法返回true。与isInterrupted()不同,它将自动重置中断状态为false,第二次调用Thread.interrupted()方法,总是返回false,除非中断了线程。
如下代码演示了Thread.interrupted()方法的使用:
- public class InterruptReset extends Object {
- public static void main(String[] args) {
- System.out.println(
- "Point X: Thread.interrupted()=" + Thread.interrupted());
- Thread.currentThread().interrupt();
- System.out.println(
- "Point Y: Thread.interrupted()=" + Thread.interrupted());
- System.out.println(
- "Point Z: Thread.interrupted()=" + Thread.interrupted());
- }
- }
运行结果如下:
从结果中可以看出,当前线程中断自身后,在Y点,中断状态为true,并由Thread.interrupted()自动重置为false,那么下次调用该方法得到的结果便是false。
补充
【Java并发编程】:线程中断的更多相关文章
- Java 并发编程 | 线程池详解
原文: https://chenmingyu.top/concurrent-threadpool/ 线程池 线程池用来处理异步任务或者并发执行的任务 优点: 重复利用已创建的线程,减少创建和销毁线程造 ...
- java并发编程 线程基础
java并发编程 线程基础 1. java中的多线程 java是天生多线程的,可以通过启动一个main方法,查看main方法启动的同时有多少线程同时启动 public class OnlyMain { ...
- java并发编程 | 线程详解
个人网站:https://chenmingyu.top/concurrent-thread/ 进程与线程 进程:操作系统在运行一个程序的时候就会为其创建一个进程(比如一个java程序),进程是资源分配 ...
- Java 并发:线程中断-interrupt
一直以为执行了interrupt方法就可以让线程结束,并抛出InterruptedException. 今天看了Java并发编程实战的第七章发现并不是这么回事,在这章的开头就提到 要使任务和线程能安全 ...
- Java并发编程:线程间通信wait、notify
Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...
- Java并发编程:线程和进程的创建(转)
Java并发编程:如何创建线程? 在前面一篇文章中已经讲述了在进程和线程的由来,今天就来讲一下在Java中如何创建线程,让线程去执行一个子任务.下面先讲述一下Java中的应用程序和进程相关的概念知识, ...
- Java并发编程——线程池的使用
在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统 ...
- Java并发编程——线程池
本文的目录大纲: 一.Java中的ThreadPoolExecutor类 二.深入剖析线程池实现原理 三.使用示例 四.如何合理配置线程池的大小 一.Java中的ThreadPoolExecutor类 ...
- Java并发编程-线程可见性&线程封闭&指令重排序
一.指令重排序 例子如下: public class Visibility1 { public static boolean ready; public static int number; } pu ...
- Java并发编程--线程封闭(Ad-hoc封闭 栈封闭 ThreadLocal)
线程封闭实现好的并发是一件困难的事情,所以很多时候我们都想躲避并发.避免并发最简单的方法就是线程封闭.什么是线程封闭呢?就是把对象封装到一个线程里,只有这一个线程能看到此对象.那么这个对象就算不是线程 ...
随机推荐
- The class cn.itcast.web.common.util.UtilFuns specified in TLD for the function selffn:htmlNewline cannot be found: cn.itcast.web.common.util.UtilFuns
我的一个Util方法的包名更改了,运行时候报这个错误.找到tld文件,把包名重新改为我改的名字就好使了.
- AngularJS标准Web业务流程开发框架—1.AngularJS模块以及启动分析
前言: AngularJS中提到模块是自定义的模块标准,提到这不得不说AngularJS是框架中的老大哥,思想相当的前卫..在这框架满天横行的时代,AngularJS有些思想至今未被超越,当然仁者见仁 ...
- 使用vbs给PPT(包括公式)去背景
在 视图—>宏 内新建宏 '终极版 Sub ReColor() Dim sld As Slide Dim sh As Shape For Each sld In ActivePresentati ...
- DVWA
DVWA默认的用户有5个,用户名密码如下(一个足以): admin/password gordonb/abc123 1337/charley pablo/letmein smithy/password
- WPF MediaKit的一点问题
原版WPF MediaKit在捕获摄像头视频时,如果不使用640*480分分辨率输出,会出现NewVideoSample事件不被触发的问题. 经数日摸索,终于明白SetVideoCapturePara ...
- C++中的关键字用法---typename
1. typename 关键字 "typename"是一个C++程序设计语言中的关键字.当用于泛型编程时是另一术语"class"的同义词.这个关键字用于指出模板 ...
- 深浅 buffer
var str = "深入浅出"; var buf = new Buffer(str, 'utf-8'); console.log(buf); 这种情况下是数字 var str = ...
- 曲演杂坛--重建索引后,还使用混合分区么?(Are mixed pages removed by an index rebuild?)
原文来自:http://www.sqlskills.com/blogs/paul/mixed-pages-removed-index-rebuild/ 在SQL SERVER 中,区是管理空间的基本单 ...
- <mvc:annotation-driven />到底帮我们做了啥
一句 <mvc:annotation-driven />实际做了以下工作:(不包括添加自己定义的拦截器) 我们了解这些之后,对Spring3 MVC的控制力就更强大了,想改哪就改哪里. s ...
- .NET 简易方法拦截器
伟大的无产阶级Willaim曾说过:"无论你觉得自己多么的了不起,也永远有人比你更强".对,我说过!我就是william. 今天想记录一下在项目中遇到的一个比较有意思的东西,异常拦 ...