InterruptedException详解

 

1.线程为什么会抛出InterruptedException?

假如现在有两个线程1和2;线程1在正常执行,此时线程2调用了线程1的interrupt方法;代码如下:

 

@RunWith(SpringJUnit4ClassRunner.class)
public class SynchronizedTest {
    @Test
    public void testSynchronized(){
        Thread thread = new Thread(){
            public void run(){
                System.out.println(Thread.currentThread().getName()+ "线程开始了~");
                System.out.println(Thread.currentThread().getName()+ "线程结束了~");
            }
        };
        thread.start();
        System.out.println("1" + thread.isInterrupted());
        thread.interrupt();
        System.out.println("2" + thread.isInterrupted());
        System.out.println("测试结束");
    }
}


运行结果如下:

1false
2true
测试结束
Thread-2线程开始了~
Thread-2线程结束了~

可以看到,正常状态的线程,在调用interrupt方法时,并不会抛出InterruptedException,而是设置一个中断状态,这个中断状态会在何时的时候起作用,也就是中断线程,具体什么时候,我们看下《java并发编程实战》中说的:
然而如果线程处于wait,sleep,join三个方法时候,则会抛出InterruptedException。我们看下代码

public void testSynchronized(){
    Thread thread = new Thread(){
        public void run(){
            System.out.println(Thread.currentThread().getName()+ "线程开始了~");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName()+"抛出了InterruptedException");
                System.out.println("2" + isInterrupted());
            }
            System.out.println(Thread.currentThread().getName()+ "线程结束了~");
        }
    };
    thread.start();
    System.out.println("1" + thread.isInterrupted());
    thread.interrupt();

    System.out.println("测试结束");


运行结果如下:
1false
测试结束
Thread-2线程开始了~
Thread-2抛出了InterruptedException
2false
Thread-2线程结束了~

可见:线程抛出了InterruptedException,但是线程的中断状态并没有变成true


2.如何处理InterruptedException?

一般来说,有三种做法:

(1)不做处理,直接抛出

直接抛出并不会影响线程的状态,被中断的线程还是会提前结束中断状态,继续执行

(2)捕获异常,再次调用interrupt方法,将中断状态重新设置为true;Thread.currentThread().interrupt();

这样就保留了线程原有的状态,让线程继续等待下去
(3)捕获异常,不处理;(不推荐)

3.正常运行的线程如何对中断状态做处理

由1我们知道,正常运行的线程在调用了interrupt方法后将中断状态设置为true,但此时线程的执行并未收到影响,如果要对线程的运行采取一些干预措施,则需要使用isInterrupt方法;还有个比较危险的方法 interrrupted(),只清除中断状态如:

if(thread.isInterrupt()){

//do Somethidng

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值