Akh
Akh

Reputation: 6043

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 i.e., it is executing the given task.

Thanks in advance.

Upvotes: 13

Views: 8935

Answers (3)

Yogesh Kumar
Yogesh Kumar

Reputation: 702

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.

Upvotes: 1

Adam Norberg
Adam Norberg

Reputation: 3076

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.

Upvotes: 10

CWMan
CWMan

Reputation: 390

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.

Upvotes: 7

Related Questions