Home > DeveloperSection > Forums > How to interrupt a Thread in Java
Samuel Fernandes
Samuel Fernandes

Total Post:154

Points:1082
Posted on    April-30-2015 12:16 AM

 Java Java  Thread 
Ratings:


 1 Reply(s)
 688  View(s)
Rate this:
Hello, i know how to interrupt a thread in java but somehow it is not working. 
My Application looks like this 
public class MyThread {
 
    public static void main(String[] args) {
        Thread testThread = new Thread(new GreatThread());
        testThread.start();
    }
     
}
public class GreatThread implements Runnable {
 
    @Override
    public void run() {
        System.out.println("I am there!");
         
        Thread.currentThread().interrupt();
         
        System.out.println("Still not interrupted!");
 
    }
 
}

Why is this not working? 
I always read that interrupting a Thread is so much better than the .stop method but somehow the interrupt method don't work? 



Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    April-30-2015 6:35 AM

Firstly you are right that the stop method should not be used. It is not safe to use and is never the correct solution
However you seem to have a misconception of what thread interrupting does. Every Thread object has a flag tracking whether the thread has been interrupted yet. When you call the interrupt method it does nothing more than set that flag. It does not cause the thread to stop executing.
It is the job of your code to detect when the thread has been interrupted, and when it has your Thread should exit as soon as possible. This is a cooperative mechanism though. If your code does not check for interruptions or ignores interruptions then the thread will continue running.

It is also not normal for a thread to interrupt itself. Normally you will interrupt a different thread when you want it to exit.

The interrupt() method doesn't immediately cause anything in the thread to happen.

However, when the thread is currently inside some blocking call, such as Thread.sleep() or another method that might throw InterruptedException, then an InterruptedException occurs in the thread, when another thread calls interrupt() on the thread.

Don't want to miss updates? Please click the below button!

Follow MindStick