8

I understand perfectly what it does (at least I hope so). It doesn't really interrupt the thread. It makes Thread.isInterrupted() true, and the code is supposed to check what method and stop the thread itself.

My question is, why do we even need this method? It seems perfectly replaceable by declaring a boolean flag stating whether this thread should be stopped? Doesn't any Java textbook use this boolean flag as the best example of how volatile keyword should be used?

I am particularly confused, as there seems to be no way to "uninterrupt" the thread, as Thread.resume() is deprecated. That makes interrupt() even less useful than a boolean flag I write by myself.

Other than being perhaps a bit easier to write, does Thread.interrupt() do anything different from my boolean flag?

CuriousMind
  • 15,168
  • 20
  • 82
  • 120

1 Answers1

7

From a related post:

Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

From javadocs

Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.

By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.

So it provides more functionality rather than simply setting a boolean flag.

Community
  • 1
  • 1
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136