What kind of behaviour causes an interrupted exception?

后端 未结 7 762
说谎
说谎 2020-12-24 13:15

I\'m relatively new to Threading in Java and I\'ve noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.

What kind of behaviour causes th

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 13:38

    It happens when something calls interrupt() on the thread. This article by Brian Goetz explains the interruption mechanism and how you should handle InterruptedExceptions:

    "The most common response to InterruptedException is to swallow it -- catch it and do nothing (or perhaps log it, which isn't any better) -- as we'll see later in Listing 4. Unfortunately, this approach throws away important information about the fact that an interrupt occurred, which could compromise the application's ability to cancel activities or shut down in a timely manner."

    "If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred [...]. This task is accomplished by calling interrupt() to "reinterrupt" the current thread."

提交回复
热议问题