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:
--
--
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | |
} | |
} | |
} | |
} |
No comments:
Post a Comment