如何在线程内部处理线程中断后的响应(重新中断)

3 篇文章 0 订阅
1 篇文章 0 订阅

最近在项目中遇到了线程中断得问题,需求如下:需要在线程被中断后及时做出相应,但是不知道线程何时被中断,因为线程中interrupt()方法只会把中断标识设置为false。

查阅资料后发现如下方法,做出分享。

public class RunAbleInterruptTest {
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            try {
                Thread.sleep(500);
                System.out.println("当前线程中断标试"+Thread.currentThread().isInterrupted());
            }catch (InterruptedException e){

                System.out.println("捕捉到当前线程中断标试"+Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("当前线程被中断:"+ Thread.currentThread().isInterrupted());
        System.out.println("可在当前处响应线程被中断后操作");


    }

    public static void main(String[] args) throws InterruptedException{
        Thread testThread=new Thread(new RunAbleInterruptTest());
        testThread.start();

        Thread.sleep(2000);
        testThread.interrupt();

    }
}

此处运用的是当线程在外部被中断后,再次调用sleep方法,会抛出InterruptedException,catch到异常以后在线程运行体中再次把当前线程中断,在while循环外部可处理当前线程被中断后的操作,这就是重新中断。

输出如下:

当前线程中断标试false
当前线程中断标试false
当前线程中断标试false
捕捉到当前线程中断标试false
当前线程被中断:true
可在当前处响应线程被中断后操作

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值