スレッドはロックやその他のリソース (ファイルなど) を保持できるため、「スレッドを強制終了」するだけではいけません。代わりに、スレッドで実行するstop
メソッドを追加します。これにより、内部フラグが設定され、メソッドで定期的にチェックされます。このような:Runnable
run
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();
}
}
さらに、 Goetz による実際の Java 並行性を読むこともできます。