要得到这个代码进行编译,我可以:
>把我的电话号码Thread.sleep()
放在try / catch块里,或者
> printAll()声明它可以抛出一个InterruptedException
.
为什么要这样做?
class Test { public static void main( String[] args ) { printAll( args ); } public static void printAll( String[] line ) { System.out.println( lines[ i ] ); Thread.currentThread().sleep( 1000 ): } }
(Kathy Sierra’s SCJP book的示例代码)
我知道Thread.sleep()抛出的异常是一个被检查的异常,所以我必须处理它,但在什么情况下Thread.sleep()需要抛出这个异常?
解决方法
如果以一种方式声明方法可以抛出已检查的异常(异常不是RuntimeException的子类),调用它的代码必须在try-catch块中调用它,或者调用方法必须声明抛出它.
Thread.sleep()
被宣布为:
public static void sleep(long millis) throws InterruptedException;
它可能会抛出InterruptedException
直接扩展java.lang.Exception
,所以你必须抓住它或声明抛出它.
为什么Thread.sleep()以这种方式声明?因为如果Thread
正在睡眠,线程可能被中断,例如与另一个线程Thread.interrupt()
,在这种情况下,休眠线程(sleep()方法)将抛出此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: t t.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)