[英]java thread interrupt, thread is null
我是線程的新手,我正在嘗試復制一個在我的網絡應用程序中中斷線程的簡單示例。 我有下面的類(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'視為null,我不知道為什么。 在testrun()中添加scan.interrupt()可以正常工作。 我想過使用Thread.currentThread()。interrupt()但是當我調用stoprun時,似乎當前的線程ID /名稱是不同的。
那是因為bean是@RequestScoped
- 每個HTTP請求(=按鈕點擊)都會獲得一個新實例。
你需要至少讓它成為@Scope("session")
。
stopRun
是第一次運行之前調用testRun
,因此該成員是null
。 這是因為每個方法調用都發生在一個新實例上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.