Skip to content

Instantly share code, notes, and snippets.

@oshi192
Last active May 7, 2018 12:56
Show Gist options
  • Save oshi192/5d8760c4e893eca058fae3598920337d to your computer and use it in GitHub Desktop.
Save oshi192/5d8760c4e893eca058fae3598920337d to your computer and use it in GitHub Desktop.

How to kill a thread?

At this moment I found 3 solutions:

Thread.stop()

The thread is forcefully stopped after a given amount of time. The Thread.stop() method causes the thread to stop what it is doing and throw a ThreadDeath exception.

final class Runner implements Runnable {
    private String name;

    Runner(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("Starting");
        int i = 0;
        while (true) {
            System.out.println(name + " " + i);
            i++;
        }
    }

}

public class Main {

    public static void main(String[] argv) throws InterruptedException {
        Runner runner = new Runner("first");
        Thread thread = new Thread(runner);
        thread.start();
        Thread.sleep(1000);
        thread.stop();
    }
}

Why is Thread.stop deprecated? Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

Thread.interrupt()

"It's just a message to the stream: "Please stop""))

In this case, the Thread.interrupt() method is called from main() to terminate the thread. Invoking Thread.interrupt() sets an internal interrupt status flag. The thread polls that flag using the Thread.interrupted() method, which both returns true if the current thread has been interrupted and clears the interrupt status flag.

final class Runner implements Runnable {
    private String name;

    Runner(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("Starting");
        int i = 0;
        while (!Thread.interrupted()) {
            System.out.println(name + " " + i);
            i++;
        }
    }

}

public class Main {

    public static void main(String[] argv) throws InterruptedException {
        Runner runner = new Runner("first");
        Thread thread = new Thread(runner);
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

Volatile flag.

This compliant solution uses a volatile flag to request thread termination. The shutdown() accessor method is used to set the flag to true. The thread's run() method polls the done flag and terminates when it is set.

final class Runner implements Runnable {
    private volatile boolean done = false;
    private String name;

    Runner(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("Starting");
        int i = 0;
        while (!done) {
            System.out.println(name + " " + i);
            i++;
        }
    }

    void shutdown() {
        done = true;
    }
}

public class Main {

    public static void main(String[] argv) throws InterruptedException {
        Runner runner = new Runner("first");
        Thread thread = new Thread(runner);
        thread.start();
        Thread.sleep(1000);
        runner.shutdown();
    }
}

more info about deprication

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment