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

gee*_*eks 22 java multithreading exception

为了编译这段代码,我可以:

为什么我要这样做?

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 ):
    }
}
Run Code Online (Sandbox Code Playgroud)

(示例代码来自Kathy Sierra的SCJP书.)

我知道Thread.sleep()抛出的异常是一个检查异常,所以我必须处理它,但在什么情况下Thread.sleep()需要抛出这个异常?

icz*_*cza 34

如果一个方法声明它可以抛出已检查的异常(Exception不是其子类RuntimeException),则调用它的代码必须在try-catch块中调用它,否则调用方法必须声明抛出它.

Thread.sleep() 声明如下:

public static void sleep(long millis) throws InterruptedException;
Run Code Online (Sandbox Code Playgroud)

它可以抛出InterruptedException直接延伸,java.lang.Exception所以你必须抓住它或声明抛出它.

为什么这样Thread.sleep()宣布?因为如果a 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!
Run Code Online (Sandbox Code Playgroud)

输出:

Sleeping...
I was interrupted!
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at Main$1.run(Main.java:13)
Run Code Online (Sandbox Code Playgroud)

  • @UnKnown相反,我们不应该打断一个线程.一种常见的技术是通知线程它应该结束它的运行,并且线程本身应该监视是否发出了这样的请求(如果是,则通过从`run()`方法返回来优雅地终止). (2认同)
  • IMO有可能从Thread.sleep中引发异常,这是糟糕的API设计 (2认同)

chi*_*ity 6

一个人Thread可以与另一个人进行交流和互动,一种Thread可以做到这一点的方法就是打断它:如果t是另一个Thread,你可以打电话t.interrupt()来礼貌地问它以阻止它目前在做什么.如果t正在睡觉,这尤其是您可能想要做的事情:您可能想要将其唤醒.它的作用是引起InterruptedException中t的Thread.sleep()方法,以便它可以捕捉到它并作出回应.因此,无论何时使用Thread.sleep()当前线程进入休眠状态,都必须处理InterruptedException其他线程决定将其唤醒的可能性.

在你的情况下,你只有一个Thread,所以你知道InterruptedException你的代码中没有其他地方.但是在多线程代码中想要做的事情并不少见.