Interrupting or stopping a sleeping thread [duplic

2019-01-11 17:22发布

问题:

This question already has an answer here:

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

How to stop or interrupt a sleeping thread in java.? I have a thread that syncs data and sleeps for 10 minutes in run() method, if i want to stop the sync by stopping the thread when it is sleeping.? How can this be achieved?

回答1:

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



回答2:

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.



回答3:

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.



回答4:

Frederik is right: call Thread.interrupt(); I just wanted to warn you not to use stop() as it is deprecated since java 1.1. And other warning. I think that if you are using sleep() and wish to interrupt the thread it is a good moment to think about move to wait() and notify(). There are many tutorials about java threads and the javadoc of java.lang.Thread is good enough, so you can continue reading there if you are not familiar with these APIs.



回答5:

Since I can't comment, I'll post another answer. I just want to reinforce and clarify what Alexandr said. interrupt() only sets a flag in the Thread, and the extended Thread or Runnable object have to check if it have been interrupted with Thread.interrupted() to do what it's supposed to do when interrupted.

interrupt() also stops a wait() or sleep(), but pay attention that those methods UNSET the interrupt flag. So, if you call interrupt() on a sleeping/waiting thread, it will stop sleeping/waiting but will not know that it was interrupted, except if you catch the exception, and will not continue to be interrupted.

I was able to fix a program of mine by implementing my own interrupt flag, which couldn't be overridden by the sleep() and wait() methods. Also, know that you can interrupt a thread from within with Thread.currentThread().interrupt().