How to interrupt a Thread in Java

Total Post:159

Java  Thread 
 1777  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());
public class GreatThread implements Runnable {
    public void run() {
        System.out.println("I am there!");
        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? 

  1. Post:397

    Re: How to interrupt a Thread in Java

    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.