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?
Anonymous User
30-Apr-2015However 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.