需要示例程序才能抛出InterruptedException

jav*_*oob 6 java multithreading

我正在通过kathy sierra SCJP 1.5第9章(线程),它被提到:

请注意,sleep()方法可以抛出已检查的InterruptedException(您通常会知道这是否可能,因为另一个线程必须明确地执行中断),因此您必须使用句柄或声明来确认异常

我只需要一个示例程序来了解它何时发生(我可以在我的机器上运行)?

我用Google搜索但找不到任何示例代码来测试此功能..

提前致谢

Jon*_*eet 25

这是一个例子:

public class Test
{
    public static void main (String[] args)
    {
        final Thread mainThread = Thread.currentThread();

        Thread interruptingThread = new Thread(new Runnable() {
            @Override public void run() {
                // Let the main thread start to sleep
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                mainThread.interrupt();
            }
        });

        interruptingThread.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("I was interrupted!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要完成它:

  • 设置一个新的线程,它将在短时间内休眠,然后中断主线程
  • 开始那个新线程
  • 长时间睡眠(在主线程中)
  • 当我们被打断时打印出一种诊断方法(再次,在主线程中)

主线程中的睡眠并不是绝对必要的,但这意味着主线程在被中断之前确实开始睡眠.