Java – why do I need to handle thread Exception of sleep()?

To get this code for compilation, I can:

>Put my phone number thread Sleep () is placed in the try / catch block, or > printall () declares that it can throw an interruptedexception

Why?

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 ):
    }
}

(example code for Kathy Sierra's scjp book)

I know thread The exception thrown by sleep () is a checked exception, so I have to deal with it, but under what circumstances thread Sleep () needs to throw this exception?

Solution

If a declarative method can throw a checked exception (exception is not a subclass of RuntimeException), the code that calls it must be invoked in the try-catch block, or the calling method must declare that it is thrown.

Thread. Sleep () is declared as:

public static void sleep(long millis) throws InterruptedException;

It may throw interruptedexception to directly extend Java Lang. exception, so you must catch it or declare to throw it

Why thread Sleep () is declared in this way? Because if the thread is sleeping, the thread may be interrupted, for example, with another thread Interrupt(), in which case the sleep thread (sleep() method) will throw an instance of this interruptedexception

Example:

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!

Output:

Sleeping...
I was interrupted!
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at Main$1.run(Main.java:13)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>