1、InterruptedException异常是什么?

官网的解释是这样的:

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

读起来很晦涩,给大家解读一下:当一个线程正在等待、休眠或被占用,并且在活动之前或期间线程被中断时抛出。

  • 等待指的是:调用Object.wait()/Object.wait(long)方法,之后进入等待状态,只等着被唤醒。没有人唤醒则一直死等。
  • 休眠指的是:调用Thread.sleep(long)方法,休息一会儿,到点之后自己醒来干活
  • 被占用指的是锁被占用,从而被迫进行堵塞。不断的监控锁,一旦有机会则上锁开始干活。

总之,以上三种情况都属于让线程放下手头上的活儿,暂停所有活动。一旦它们重启干活儿,则需要向外界发送信号,告知一下,这就是中断。中断属于信号而已,但是在Java里面被归入了异常,所以有了:InterruptedException异常。

2、InterruptedException异常使用场景1

public class Test
{

    public static void main(String[] args)
    {
        Thread.sleep(1000);
        System.out.println("hello world!");
    }

}

如上所述,main线程要先睡上1000毫秒,睡醒之后它要发出中断信号,告诉CPU它醒来了。但是,在Java语言里面没有信号机制,所以JDK的作者只能煞费苦心进行改造,从异常入手进行改造:InterruptedException,改造后的代码就是这样的:

public class Test
{

    public static void main(String[] args) throws InterruptedException
    {
        Thread.sleep(1000);
        System.out.println("hello world!");
    }

}

main线程抛出异常就是要告诉调用main线程的JVM进程,它已经睡醒了,可以继续干活了。JVM进程看到这个异常明白什么意思,不需要做额外处理。

3、InterruptedException异常使用场景2

InterruptedException异常仅仅是信号,可以利用其信号机制,如下所示:

try 
{  
    TimeUnit.SECONDS.sleep(2);  
} 
catch (InterruptedException e) 
{  
    //收到信号之后,可以做些其他的操作 
} 
public class Test
{

    public static void main(String[] args)
    {
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            System.err.println("InterruptedException caught!");
            e.printStackTrace();
        }
        System.out.println("hello world!");
    }

}

main线程自己消化异常,不向外抛出。

标签: none

[网站公告]-[2024年兼职介绍]


添加新评论