如果以一种可以引发检查异常的方式声明方法(
Exception不是的子类
RuntimeException),则调用该方法的代码必须在一个
try-catch块中调用它,否则调用者方法必须声明以引发它。
Thread.sleep()声明如下:
public static void sleep(long millis) throws InterruptedException;
它可能会抛出
InterruptedException并直接延伸,
java.lang.Exception因此您必须抓住它或声明将其抛出。
为什么要这样
Thread.sleep()声明?因为如果a
Thread正在睡眠,则该线程可能被
Thread.interrupt()另一个线程中断,在这种情况下,睡眠线程(该
sleep()方法)将抛出this的一个实例
InterruptedException。
例:
Thread t = new Thread() { @Override public void run() { try { System.out.println("Sleeping..."); Thread.sleep(10000); System.out.println("Done sleeping, no interrupt."); } catch (InterruptedException e) { System.out.println("I was interrupted!"); e.printStackTrace(); } }};t.start(); // Start another thread: tt.interrupt(); // Main thread interrupts t, so the Thread.sleep() call // inside t's run() method will throw an InterruptedException!输出:
Sleeping...I was interrupted!java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at Main$1.run(Main.java:13)



