Reputation: 1631
I want to interrupt a thread, but invoking interrupt()
doesn't seem to work. Below is the sample code:
public class BasicThreadrRunner {
public static void main(String[] args) {
Thread t1 = new Thread(new Basic(), "thread1");
t1.start();
Thread t3 = new Thread(new Basic(), "thread3");
Thread t4 = new Thread(new Basic(), "thread4");
t3.start();
t1.interrupt();
t4.start();
}
}
class Basic implements Runnable{
public void run(){
while(true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("thread: " + Thread.currentThread().getName());
//e.printStackTrace();
}
}
}
}
but the output looks like thread 1 is still running. Can anyone explain this as well as how interrupt()
works? Thanks!
Upvotes: 8
Views: 18924
Reputation: 891
++1, in addition to other answers. I believe the misconception about this was that it seemed the try/catch
block finished its job after the Thread.sleep(1000);
call i.e. try to sleep for 1000ms, catch anything that might interrupt my sleep attempt.
What is happening actually is that the try/catch
block is still very much active while sleeping i.e. try to sleep for 1000ms, catch anything that might interrupt during my sleep
Hence the reason why the exception is being caught immediately (and afterwards) since the thread barely just started its sleep.
Upvotes: 0
Reputation: 44240
As others have said, you catch the interrupt, but do nothing with it. What you need to do is propagate the interrupt using logic such as,
while(!Thread.currentThread().isInterrupted()){
try{
// do stuff
}catch(InterruptedException e){
Thread.currentThread().interrupt(); // propagate interrupt
}
}
Using looping logic, such as while(true)
is just lazy coding. Instead, poll the thread's interrupted flag in order to determine termination via interruption.
Upvotes: 18
Reputation: 81674
The thread is still running simply because you catch InterruptedException
and keep running. interrupt()
primarily sets a flag in the Thread
object, which you can check with isInterrupted()
. It also causes some methods -- sleep()
, join
Object.wait()
, in particular -- to return immediately by throwing an InterruptedException
. It also causes some I/O operations to immediately terminate. If you're seeing the printouts from your catch
block, then you can see that interrupt()
is working.
Upvotes: 18