java – 为什么需要处理Thread.sleep()的异常?

要得到这个代码进行编译,我可以:

>把我的电话号码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)

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...