加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:20:07 所属栏目:Java 来源:网络整理
导读:要得到这个代码进行编译,我可以: 把我的电话号码 Thread.sleep() 放在try / catch块里,或者 printAll()声明它可以抛出一个 InterruptedException . 为什么要这样做? class Test { public static void main( String[] args ) { printAll( args ); } public
要得到这个代码进行编译,我可以:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读