我正在通过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
我只需要一个示例程序来了解它何时发生(我可以在我的机器上运行)?
提前致谢
解决方法
这是一个例子:
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!"); } } }
要完成它:
>设置一个新的线程,它将暂停一段时间,然后中断主线程
>开始新的线程
>长时间睡眠(在主线程中)
>当我们被打断时打印出一种诊断方法(再次,在主线程中)
主线程中的睡眠并不是绝对必要的,但这意味着主线程在被中断之前确实开始睡眠.