java – 需要示例程序来抛出InterruptedException

前端之家收集整理的这篇文章主要介绍了java – 需要示例程序来抛出InterruptedException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在通过kathy sierra SCJP 1.5第9章(线程),它被提到:

Notice that the sleep() method can throw a checked InterruptedException
(you’ll usually know if that is a possibility,since another thread has to explicitly do
the interrupting),so you must acknowledge the exception with a handle or declare

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

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

提前致谢

解决方法

这是一个例子:
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!");
        }
    }
}

要完成它:

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

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

原文链接:https://www.f2er.com/java/127614.html

猜你在找的Java相关文章