Saturday, 15 July 2017

How do we stop a thread in Java?

To stop a thread one can use a volatile reference pointing to the current thread that can be set to null by other threads to indicate the current thread should stop its execution:

--
private static class MyStopThread extends Thread {
private volatile Thread stopIndicator;
public void start() {
stopIndicator = new Thread(this);
stopIndicator.start();
}
public void stopThread() {
stopIndicator = null;
}
@Override
public void run() {
Thread thisThread = Thread.currentThread();
while(thisThread == stopIndicator) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


No comments:

Post a Comment