Java 线程interrupt总结

一、java Thread常见状态有:NEW=新建,RUNNABLE=运行,TERMINATED=中断,BLOCKED=阻塞,WAITING状态时会=等待,SLEEPING=休眠。

二、线程中断interrupt():
1、A线程调用B.interrupt()中断B时若B在SLEEPING或者WAITING状态时会出现InterruptedException,此时B线程跳出当前代码块并执行完剩余的代码;此时调用isInterrupted()获取B线程状态为false。
2、如需依赖中断状态处理逻辑必须在扑火InterruptedException异常并再次进行中断Thread.currentThread().interrupt();再次中断后isInterrupted()获取B线程状态为true。此时需调用return结束当前线程任务,否则余下代码仍会继续执行。
3、不管强制中断与否B线程执行完毕后,isInterrupted()重置为false。

测试代码如下:
public class ThreadTest {

public static void main(String[] args){

    Thread a;

    a = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("1"+Thread.currentThread().isInterrupted());

                Thread.sleep(5000);
                System.out.println("2"+Thread.currentThread().isInterrupted());

            } catch (InterruptedException e) {
                System.out.println("3"+Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
                System.out.println("3.5"+Thread.currentThread().isInterrupted());

                e.printStackTrace();
                return;
            }

            System.out.println("4"+Thread.currentThread().isInterrupted());
        }
    });
    a.start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    a.interrupt();
    System.out.println("5"+a.isInterrupted());

    try {
        Thread.sleep(6000);
        System.out.println("6"+a.isInterrupted());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

    直接中断测试结果:

在这里插入图片描述
捕获异常进行中断并return:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值