Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 600
Akh Avatar asked Dec 06 '10 22:12

Akh


2 Answers

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.

like image 103
Adam Norberg Avatar answered Oct 31 '22 23:10

Adam Norberg


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.

like image 24
yug Avatar answered Oct 31 '22 23:10

yug