简体   繁体   中英

What happens when you invoke a thread's interrupt()?

I need to know what happens

  1. when it is sleeping?
  2. when it is running ie, it is executing the given task.

Thanks in advance.

Interrupting a thread is a state-safe way to cancel it, but the thread itself has to be coded to pay attention to interrupts. Long, blocking Java operations that throw InterruptedException will throw that exception if an .interrupt() occurs while that thread is executing.

The .interrupt() method sets the "interrupted" flag for that thread and interrupts any IO or sleep operations. It does nothing else, so it's up to your program to respond appropriately- and check its interrupt flag, via Thread.interrupted() , at regular intervals.

If a thread doesn't check for interruptions, it cannot safely be stopped. Thread.stop() is unsafe to use. So you use .interrupt() to stop a thread, but when writing multithreaded code, it is up to you to make sure that .interrupt() will do something sensible. This TechRepublic article is a pretty good tutorial.

Judging by your previous questions, I assume you are interested in Java's behavior.

In Java, an InterruptedException will be thrown if the thread is currently blocking. If the thread is not blocking, the exception will not be thrown.

For more information, look here:
JavaDocs

For .NET languages, a ThreadInterruptedException will be thrown if the thread is currently blocking. If the thread isn't blocking the exception will not be thrown until the thread blocks.

Please tag your question with the language you want an answer for.

One more important information worth sharing is that, there are two methods in Thread Class isInterrupted() and interrupted() . Latter one being a static method. isInterrupted() method call does not alter the state of interrupted attribute of Thread class, whereas interrupted() static method call can will set the value of interrupted boolean value to false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM