博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程中断处理
阅读量:3962 次
发布时间:2019-05-24

本文共 1754 字,大约阅读时间需要 5 分钟。

一、线程中断的方法

线程中断方法主要是两种:

.isInterrupted()是否为中断状态
interrupt()设置为中断

线程中断,并非真正的线程中断,而只是将线程的中断状态标识设置为true,由线程自己根据状态标识进行相应的业务处理逻辑,而线程实际上还在进行。

要区别于InterruptedException异常,一般的,线程会因为BlockingQueue#put、BlockingQueue#take、Object#wait、Thread#sleep以上状态被打断而抛出异常,这个异常是真正的线程中断,而与线程的中断状态标识没有任何关系,标识状态依然为false。

所以,这就需要注意一个问题,千万不能捕获了InterruptedException而不做中断处理,否则业务逻辑依然以为你没有中断,依然走正常的异常逻辑

二、示例代码

@Testpublic void testThread() throws InterruptedException {
testThread1(); testThread2();}private void testThread1() throws InterruptedException {
Thread thread1 = new Thread(() -> {
//判断当前线程的中断状态,否则执行,是则中断 while (!Thread.currentThread().isInterrupted()) {
System.out.println("正常业务"); } System.out.println("中断业务"); }, "thread1"); thread1.start(); Thread.sleep(3000L); //中断线程1,并非真正的停止线程,而是将中断状态标识为true,由线程自己处理 thread1.interrupt();}private void testThread2() throws InterruptedException {
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
boolean interrupted = Thread.currentThread().isInterrupted(); System.out.println("中断状态:" + interrupted); if (!interrupted) {
try {
System.out.println("业务逻辑"); Thread.sleep(3000);//模拟实际逻辑 } catch (InterruptedException e) {
/*不可以吞掉异常,因为中断状态不会因为抛出异常而将interrupted改为true 故,必须设置中断,从而可以走中断业务逻辑 */ Thread.currentThread().interrupt(); } } else {
System.out.println("中断业务逻辑"); } } }, "thread2"); thread2.start(); Thread.sleep(1000); thread2.interrupt();//模拟执行的正常业务逻辑出现异常}

转载地址:http://jtgzi.baihongyu.com/

你可能感兴趣的文章
复合语句(compound statement)
查看>>
DB2 物化查询表
查看>>
IF 语句
查看>>
循环语句
查看>>
DB2 临时表
查看>>
ITERATE、LEAVE、GOTO和RETURN
查看>>
异常处理
查看>>
存储过程
查看>>
动态SQL(Dynamic SQL)
查看>>
在存储过程之间传递数据
查看>>
迁移存储过程
查看>>
GET DIAGNOSTIC 语句
查看>>
用户自定义函数
查看>>
内联 SQL PL(Inline SQL PL)
查看>>
触发器(Trigger)
查看>>
锁升级失败将引起死锁
查看>>
DB2 目录结构
查看>>
Python 精萃
查看>>
Python 简介
查看>>
Python 注释
查看>>