我是线程新手,正在尝试复制一个在我的网络应用程序中中断线程的简单示例。我有下面的类(ComputeResults 有其他变量和函数、setter/getters 等,但这是我无法工作的新代码):
@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”函数将“scan”视为空,我不确定为什么。在 testrun() 中添加 scan.interrupt() 效果很好。我想过使用 Thread.currentThread().interrupt() 但当我调用 stoprun 时,当前线程 ID/名称似乎不同。
最佳答案
这是因为 bean 是 @RequestScoped
- 每个 HTTP 请求(= 按钮单击)都会获取一个新实例。
您至少需要将其设为@Scope("session")
。
关于java线程中断,线程为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068230/