Reputation: 1982
I have got this piece of code:
public class ThreadInteraction {
public static void main(String[] argv) {
System.out.println("Create and start a thread t1, then going to sleep...");
Thread1 t1 = new Thread1();
t1.start();
try{
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println(e.toString());
}
//let's interrupt t1
System.out.println("----------- Interrupt t1");
t1.interrupt();
for(int i =0; i<100; i++)
System.out.println("Main is back");
}
}
class Thread1 extends Thread {
public void run() {
for(int i =0; i<10000; i++)
System.out.println(i + "thread1");
}
}
It seems like t1.interrupt()
doesn't work as in my output all 10000 t1 print appears. Am I doing something wrong?
Upvotes: 2
Views: 799
Reputation: 41510
Thread.interrupt()
actually doesn't stop anything. This method is meant to only set the interrupted state of the thread, but you have to check for it. This is how you should organize your code in order to make it work:
public void run() {
for (int i = 0; i < 10000; i++) {
if (interrupted()) break;
System.out.println(i + "thread1");
}
}
Thread.interrupted()
here clears the interrupted state, which is OK since we control the thread directly. If you try to detect interruptions, for example, in java.util.concurrent. Callable
which runs on one of the threads of a thread pool, then it is better to use Thread.currentThread().isInterrupted();
since you don't know the thread interruption policy.
Upvotes: 5
Reputation: 206659
Thread.interrupt
will only cause the target thread to stop if it is in very specific states:
First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
You need to check isInterrupted
in your thread if you want it to exit that loop early.
for(int i =0; i<10000 && !isInterrupted(); i++)
Upvotes: 1