从主线程休眠是抛出InterruptedException [英] sleep from main thread is throwing InterruptedException

查看:112
本文介绍了从主线程休眠是抛出InterruptedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有执行的主线程产生新线程。在main()的主要执行线程中,我调用 Thread.sleep()。我何时才能获得未处理的异常类型 InterruptedException

I have the main thread of execution which spawns new threads. In the main thread of execution in main() I am calling Thread.sleep(). When do I get an Unhandled exception type InterruptedException?.

我不确定为什么会得到这个。我认为这是因为我需要对主线程的引用所以我继续通过 Thread.currentThread()来引用它。

I am unsure of why am I getting this. I thought this was because I needed a reference to the main thread so I went ahead and made a reference to it via Thread.currentThread().

这不是线程睡眠的方法吗?我需要做的是让主线程等待/睡眠/延迟,直到它再次需要工作。

Is this not the way to have the thread sleep? What I need to do is have the main thread wait/sleep/delay till it does it required work again.

推荐答案

您看到的是编译错误,因为您没有处理已检查的异常(在这种情况下InterruptedException 正确。处理意味着执行以下操作之一:

What you see is a compilation error, due to the fact that you didn't handle the checked exception (InterruptedException in this case) properly. Handling means doing one of the following:

1)将方法声明为会抛出InterruptedException ,因此需要调用者处理异常

1) Declaring the method as throws InterruptedException, thus requiring the caller to handle the exception

2)用抓住它{}} catch(..){..} 阻止。例如:

try {
    Thread.sleep(1500);
} catch(InterruptedException e) {
    System.out.println("got interrupted!");
}

使用InterruptedException 指示当前线程在执行某些阻塞操作时被外部线程中断(例如可中断IO,等待,休眠)

InterruptedException is used to indicate that the current thread has been interrupted by an external thread while it was performing some blocking operation (e.g. interruptible IO, wait, sleep)

这篇关于从主线程休眠是抛出InterruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆