What kind of behaviour causes an interrupted exception?

后端 未结 7 763
说谎
说谎 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

    As others have said, it is caused by some other thread calling interrupt() on the Thread object that is sleeping.

    What this means in plain english, is that some other thread has decided to cancel the sleeping thread. The try/catch block is there so you can gracefully handle the cancellation of the thread, and safely clean up any resources, or shut down whatever operation it was doing correctly.

    If you don't actually need to do any of that, then yes, you still need an empty catch block. But that's Java for you...​​​​​​​​​​​​​​​​​​​​

提交回复
热议问题