いくつかの入力を受け取り、それらに対してアルゴリズムを実行するプログラムの GUI を作成しています。アルゴリズムのコードはかなり長く複雑なので、入力の計算を実行するために GUI から新しいスレッドを起動しました。
//algorithmThread previously initialized
if(e.getSource() == startButton) {
if(update.updateStrings(textFields)) {
algorithmThread.start();
}
}
ユーザーが間違った入力ファイルを提供した場合に、ユーザーが計算を停止できるようにする機能を追加したいと考えています (私のラップトップでは、結果が生成されるまでに約 30 分実行されます)。これが私がそれを処理する方法です。
else if(e.getSource() == stopButton) {
//if the user presses the stop button then intterupt the
//thread running the algorithm
algorithmThread.interrupt();
System.out.println("algorithm stopped"); //debugging code
//recreate the thread in case the user hits the start button again
algorithmThread = new Thread() {
public void run() {
runNOC();
}
};
}
プログラムはアルゴリズムを正常に停止し(例外処理を行う必要があると思いますが)、ユーザーが新しい入力を入力して再起動できるようにします。私の質問は、アルゴリズムのコードで Thread.interrupted() をチェックする必要があるのはどのような条件ですか? 必要/ベストプラクティスですか?または、上記の方法でスレッドを停止することは許容されますか?