sleep from main thread is throwing InterruptedException

前端 未结 3 2032
后悔当初
后悔当初 2021-01-04 12:52

I have the main thread of execution which spawns new threads. In the main thread of execution in main() I am calling Thread.sleep(). When do I get an Unhand

3条回答
  •  走了就别回头了
    2021-01-04 13:14

    What you see is a compilation error, due to the fact that you didn't handle the checked exception (InterruptedException in this case) properly. Handling means doing one of the following:

    1) Declaring the method as throws InterruptedException, thus requiring the caller to handle the exception

    2) Catching it with a try{..}catch(..){..} block. For example:

    try {
        Thread.sleep(1500);
    } catch(InterruptedException e) {
        System.out.println("got interrupted!");
    }
    

    InterruptedException is used to indicate that the current thread has been interrupted by an external thread while it was performing some blocking operation (e.g. interruptible IO, wait, sleep)

提交回复
热议问题