我是新来的线程,并试图复制一个简单的例子,在我的web应用程序中中断一个线程。我有下面的类(ComputeResults有其他的变量和函数,制定者/吸气等,但,这是新的代码,我不能去上班):java线程中断,线程为空
@ManagedBean(name="results")
@RequestScoped
public class ComputeResults implements Serializable{
Thread scan;
public void testrun() {
scan = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (!Thread.currentThread().isInterrupted()) {
try {
i++;
if (i == 1) {
scan.interrupt();
}
}
catch (Exception e) {
Thread.currentThread().interrupt();
}
catch (Throwable t) {
System.out.println("Thrown test: "+t.getMessage());
}
}
}
});
scan.start();
}
public void stoprun() {
if(scan != null){
scan.interrupt();
}
}
}
在我的界面我有一个按钮,启动线程:
<p:commandLink action="submit" value="" onclick="testdialog.show()" oncomplete="testdialog.hide()" actionListener="#{results.testrun}" update="messages, runmsg, @form results" />
和一个试图打断它:
<p:commandButton action="submit" value="Cancel Test" onclick="testdialog.hide()" actionListener="#{results.stoprun}" update="messages, runmsg" />
问题是“STOPRUN”功能看到“扫描”为空,我不知道为什么。在testrun()内部添加scan.interrupt()可以正常工作。我想过使用Thread.currentThread().interrupt(),但似乎当我调用stoprun时,当前线程ID /名称是不同的。
@RequestScoped - 这是不是意味着范围只持续一个http请求,所以它不会被保留在下一个? – eis
我明白了,yep是有道理的,我专注于功能,忘记了豆的范围,会试试看,谢谢! – Alaph432