You must not just "kill thread", since thread can hold locks or other resources (like files). Instead add stop
method to Runnable
you execute in thread, which will set internal flag and check it in run
method periodically. Like this:
class StopByPollingThread implements Runnable {
private volatile boolean stopRequested;
private volatile Thread thisThread;
synchronized void start() {
thisThread = new Thread(this);
thisThread.start();
}
@Override
public void run() {
while (!stopRequested) {
// do some stuff here
// if stuff can block interruptibly (like calling Object.wait())
// you'll need interrupt thread in stop() method as well
// if stuff can block uninterruptibly (like reading from socket)
// you'll need to close underlying socket to awake thread
try {
wait(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized void requestStop() {
stopRequested = true;
if (thisThread != null)
thisThread.interrupt();
}
}
Additionally, you may want to read Java concurrency in practice by Goetz.