我是线程的新手,正在尝试在我的web应用程序中复制一个中断线程的简单示例。我有下面的类(ComputeResults有其他的变量和函数,setter/getter等,但这是我不能使用的新代码):
@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’视为null,我不确定为什么。在testrun()中添加scan.interrupt()可以很好地工作。我考虑过使用Thread.currentThread().interrupt(),但是当我调用stoprun时,当前的线程ID/名称似乎不同了。
发布于 2012-08-22 15:34:53
这是因为bean是单击的--每个HTTP请求(= @RequestScoped )都会获得一个新的实例。
你至少需要让它成为@Scope("session")。
发布于 2012-08-22 15:36:30
在第一次运行testRun之前调用了stopRun,因此该成员为null。这是因为每个方法调用都发生在一个新的实例上。
https://stackoverflow.com/questions/12068230
复制相似问题