加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:33:44 所属栏目:Java 来源:网络整理
导读:我正在通过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
我正在通过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!");
        }
    }
}

要完成它:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读