线程中断interrupt


public class ThreadInterrupt {
    public static void main(String[] args) throws InterruptedException {
        Thread1 t1 = new Thread1();
        Thread2 t2 = new Thread2();
        t1.start();
       // t2.start();
        Thread.sleep(200);
        System.out.println("t1被中断");
        t1.interrupt();
        Thread.sleep(2000000);
    }
}
class Thread1 extends Thread{

    @Override
    public void run() {
        int i=0;
        while(true){
            System.out.println(Thread.currentThread().isInterrupted());
            if(!Thread.currentThread().isInterrupted()){
                System.out.println("线程:"+Thread.currentThread().getName()+"run..."+i);
                i++;
            }else{
                System.out.println(Thread.currentThread().getName()+"--EXIT");
                break;
            }
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                System.out.println("线程被中断.."+Thread.currentThread().getName());
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }
}
class Thread2 extends Thread{

    @Override
    public void run() {
        int i=0;
        while(true){
            if(!Thread.currentThread().isInterrupted()){
                System.out.println("线程"+Thread.currentThread().getName()+"run.."+"aa");
            }
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                System.out.println("线程被中断.."+Thread.currentThread().getName());
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }
}

因为在wait或者在sleep的时候也可以随时被中断的,即要随时对interrupt做出相应;当程序在sleep的过程中被中断,那么程序会跳到catch中去,抛出中断异常;当线程抛出异常中断异常的时候会清空中断标志位,所以在catch中要再次设置中断标志位,如果不设置的话程序仍然会继续执行,不会被真正的中断



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值