Interrupting or stopping a sleeping thread

This question already has an answer here:

  • How can I kill a thread? without using stop(); 3 answers

  • Call the interrupt() method on your thread. This will cause the sleep to be cancelled and an InterruptedException will be thrown.


    You can interrupt a sleeping thread with Thread.interrupt() . Now stopping a thread is deprecated - what if the thread is holding a lock to something? (There was a Thread.stop() , but it is HIGHLY discouraged).

    Alternatively, instead of sleeping, you can have your thread wait for an object to be notified with a timeout, and simplify notify the object if you want the thread to wake up.


    Suresh, I wish to pay attention to one issue. interrupt() methods itself does not interrupt thread. It just sends a request to a thread for interruption, by setting the flag to true. Usually your thread should process cancellation/interruption policy. It is greatly described in Java Concurrecy in Practice, section 7.1 Task Cancellation.

    Blocking library methods such Thread.sleep and Object.wait try to detect when a thread has been interrupted and return early. They respond to interruption by clearing the interrupted status and throwing InterruptedException.

    链接地址: http://www.djcxy.com/p/16396.html

    上一篇: 原生方法的源代码是否可用?

    下一篇: 中断或停止睡眠线程