Java中的 InterruptedException 异常

什么是InterruptedException异常


Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:

这是jdk中对InterruptedException异常的解释,简单来说就是当阻塞方法收到中断请求的时候就会抛出InterruptedException异常,当一个方法后面声明可能会抛出InterruptedException 异常时,说明该方法是可能会花一点时间,但是可以取消的方法。

抛InterruptedException的代表方法有:sleep(),wait(),join()

 

 

是谁抛出InterruptedException异常

上面说到,抛InterruptedException的代表方法有:sleep(),wait(),join()

执行wait方法的线程,会进入等待区等待被notify/notify All。在等待期间,线程不会活动。

执行sleep方法的线程,会暂停执行参数内所设置的时间。

执行join方法的线程,会等待到指定的线程结束为止。

因此,上面的方法都是需要花点时间的方法。这三个方法在执行过程中会不断轮询中断状态(interrupted方法),从而自己抛出InterruptEdException。

interrupt方法其实只是改变了中断状态而已。

所以,如果在线程进行其他处理时,调用了它的interrupt方法,线程也不会抛出InterruptedException的,只有当线程走到了sleep, wait, join这些方法的时候,才会抛出InterruptedException。若是没有调用sleep, wait, join这些方法,或者没有在线程里自己检查中断状态,自己抛出InterruptedException,那InterruptedException是不会抛出来的。

 

 

例子

public class test2 {

    private static class test extends Thread {
        @Override
        public void run() {
            try {
                //如果注释掉下面这句,则不会捕获到InterruptedException
                Thread.sleep(2000);
                System.out.println("test run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public static void main(String[] args) throws InterruptedException {
    Thread test = new test();
    test.start();
    test.interrupt();
    System.out.println("test run");
}

如果去掉Thread.sleep(2000),执行test.interrupt()方法是不会抛出InterruptedException异常的,因为interrupt()方法只是改变了中断状态,具体判断这个状态抛出异常的动作是在sleep方法中完成的。

 

你可能感兴趣的:(java基础)