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?
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:Thread.interrupted()here clears the interrupted state, which is OK since we control the thread directly. If you try to detect interruptions, for example, injava.util.concurrent. Callablewhich runs on one of the threads of a thread pool, then it is better to useThread.currentThread().isInterrupted();since you don’t know the thread interruption policy.