【发布时间】:2013-10-05 12:12:42
【问题描述】:
我正在为一个程序编写一个 GUI,该程序接受一些输入并在其上运行算法。该算法的代码相当长且复杂,因此我刚刚从 GUI 启动了一个新线程,以便对输入执行计算。
//algorithmThread previously initialized
if(e.getSource() == startButton) {
if(update.updateStrings(textFields)) {
algorithmThread.start();
}
}
我们希望添加允许用户在提供错误输入文件的情况下停止计算(它在我的笔记本电脑上运行大约半小时然后产生结果)的功能。这就是我的处理方式。
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() ?是否有必要/最佳实践?或者按上面说明的方式停止线程是否可以接受?
【问题讨论】:
-
this link 会帮助你
-
你的方法很好。您检查中断标志的频率将直接与用户单击“停止”按钮后线程停止其工作所需的时间...
标签: java multithreading