一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。

InterruptedException

通过调用一个线程的 interrupt() 来中断该线程,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException,从而提前结束该线程。但是不能中断 I/O 阻塞和 synchronized 锁阻塞。

对于以下代码,在 main() 中启动一个线程之后再中断它,由于线程中调用了 Thread.sleep() 方法,因此会抛出一个 InterruptedException,从而提前结束线程,不执行之后的语句。

public class InterruptExample {private static class MyThread1 extends Thread {@Overridepublic void run() {try {Thread.sleep(2000);System.out.println("Thread run");} catch (InterruptedException e) {e.printStackTrace();}}}
}
public static void main(String[] args) throws InterruptedException {Thread thread1 = new MyThread1();thread1.start();thread1.interrupt();System.out.println("Main run");
}
Main run
java.lang.InterruptedException: sleep interruptedat java.lang.Thread.sleep(Native Method)at InterruptExample.lambda$main$0(InterruptExample.java:5)at InterruptExample$$Lambda$1/713338599.run(Unknown Source)at java.lang.Thread.run(Thread.java:745)

interrupted()

如果一个线程的 run() 方法执行一个无限循环,并且没有执行 sleep() 等会抛出 InterruptedException 的操作,那么调用线程的 interrupt() 方法就无法使线程提前结束。

但是调用 interrupt() 方法会设置线程的中断标记,此时调用 interrupted() 方法会返回 true。因此可以在循环体中使用 interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程。

public class InterruptExample {private static class MyThread2 extends Thread {@Overridepublic void run() {while (!interrupted()) {// ..}System.out.println("Thread end");}}
}
public static void main(String[] args) throws InterruptedException {Thread thread2 = new MyThread2();thread2.start();thread2.interrupt();
}
Thread end

Executor 的中断操作

调用 Executor 的 shutdown() 方法会等待线程都执行完毕之后再关闭,但是如果调用的是 shutdownNow() 方法,则相当于调用每个线程的 interrupt() 方法。

以下使用 Lambda 创建线程,相当于创建了一个匿名内部线程。

public static void main(String[] args) {ExecutorService executorService = Executors.newCachedThreadPool();executorService.execute(() -> {try {Thread.sleep(2000);System.out.println("Thread run");} catch (InterruptedException e) {e.printStackTrace();}});executorService.shutdownNow();System.out.println("Main run");
}
Main run
java.lang.InterruptedException: sleep interruptedat java.lang.Thread.sleep(Native Method)at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745)

如果只想中断 Executor 中的一个线程,可以通过使用 submit() 方法来提交一个线程,它会返回一个 Future<?> 对象,通过调用该对象的 cancel(true) 方法就可以中断线程

Future<?> future = executorService.submit(() -> {// ..
});
future.cancel(true);

多线程:中断(interrupt、interrupted、executor)相关推荐

  1. 中断(interrupted()、isInterrupted())、Executor的中断

    1. 中断 一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束. InterruptedException通过调用一个线程的 interrupt() 来中断该线程,如果该线程处于阻塞 ...

  2. 【面试:并发篇09:多线程:interrupt 方法详解】

    [面试:并发篇09:多线程:interrupt 方法详解] 00.前言 如果有任何问题请指出,感谢. 01.介绍 程序中,有些线程的中断需要外部干预,比如线程中存在while(true)循环,或者存在 ...

  3. java 线程 通过interrupted_Java线程的传说(1)——中断线程Interrupted的用处

    中断线程 -- interrupt() 一个正在运行的线程除了正常的时间片中断之外,能否被其他线程控制?或者说其他线程能否让指定线程放弃CPU或者提前结束运行? 除了线程同步机制之外,还有两种方法: ...

  4. 关于interrupt(),interrupted(),isInterrupted()用法分析

    我想代码是非常容易解释这个问题的了.下文会给出总结. 总结点击这里或者往下阅读: 直接来一段小代码吧: public class Interrupt {public static void main( ...

  5. isInterrupted() interrupt() interrupted() 方法的简单解释

    isInterrupted() interrupt() interrupted() 方法的简单解释 1.isInterrupted() 和 interrupt() 是实例方法,必须要通过对象实例来调用 ...

  6. java线程的中断(interrupt)

    一个线程在未正常结束之前, 被强制终止是很危险的事情. 因为它可能带来完全预料不到的严重后果比如会带着自己所持有的锁而永远的休眠,迟迟不归还锁等. 所以你看到Thread.suspend, Threa ...

  7. 多线程之 interrupt,interrupted,isInterrupted 方法区别

    首先看测试代码 /** * Created by Jarvis.y on 2020/11/5 * <p> * interrupt , interrupted , isInterrupted ...

  8. java中interrupt,interrupted和isInterrupted的区别

    文章目录 isInterrupted interrupted interrupt java中interrupt,interrupted和isInterrupted的区别 前面的文章我们讲到了调用int ...

  9. java终端线程_java多线程-中断线程

    大纲: java线程的中断原则 中断相关方法 中断实例 一.java线程中断原则 java中断是一种协作机制,每一个线程的中断都由线程自己处理,其他线程只是给要中断的线程一个中断标志. 二.相关方法 ...

  10. java并发编程之正确地终止一个线程interrupt/interrupted

    以下demo是错误的终止线程的demo(使用thread.stop()方法实现终止线程): public class ErrorStopThreadDemo {public static void m ...

最新文章

  1. 按拼音模糊匹配查询条件的生成类
  2. 特斯拉撤诉和解,小鹏汽车沉冤得雪:警惕自动驾驶领域的“美国陷阱”
  3. Nginx服务器编译添加SSL模块
  4. python 提示错误AttributeError: type object 'str' has no attribute '_name_'
  5. android之SharedPreferences
  6. Gradle——创建简单的项目
  7. c++ 退出函数_UCOSIII源码分析之——bsp_os.c文件分析
  8. Java编程基础03——进制运算数据类型变量
  9. RedHat 下载地址
  10. java web 车辆管理系统_javaweb车辆信息管理系统
  11. 计算机主机ppt课件,怎么用电脑制作ppt课件
  12. 算法入门:股票最大收益
  13. 90后男屌丝如何让淘宝客日赚10万滴
  14. java疯狂讲义3_java8--IO(java疯狂讲义3复习笔记)
  15. 好用的电台APP推荐|这些年,陪伴我上下班的声音
  16. 高校成绩管理数据库系统的设计与实现
  17. 金融风控项目(数据分析最后阶段精华总结很久!)
  18. 【ASE入门学习】ASE入门系列六——塞尔达扰动火焰
  19. 埃拉托斯特尼(Eratosthene)筛法
  20. 【DNS】Windows查看和清理DNS缓存

热门文章

  1. OCR磁盘的导出和导入、备份和恢复以及移动(ocrconfig命令的应用)
  2. Linux命令——cp
  3. cocos2d-x按钮CCControlButton的用法
  4. php用Simple Excel导出xls
  5. [置顶] HTML5 实现小车动画效果(Canvas/CSS3/JQuery)
  6. asp.net 连接 Access 的几种方法
  7. 《深入解析Windows操作系统》--第一章 概念和工具
  8. linux shell编程控制结构:expr、let、for、while、until、shift、if、case、break、continue、函数、select 学习笔记
  9. 孤儿进程与僵尸进程[总结]
  10. [Linux] killall 、kill 、pkill 命令详解