2012-08-22 78 views
0

我是新來的線程,並試圖複製一個簡單的例子,在我的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 /名稱是不同的。

+1

@RequestScoped - 這是不是意味着範圍只持續一個http請求,所以它不會被保留在下一個? – eis

+0

我明白了,yep是有道理的,我專注於功能,忘記了豆的範圍,會試試看,謝謝! – Alaph432

回答

2

這是因爲這個bean是@RequestScoped - 每個HTTP請求(=按鈕點擊)都會得到一個新的實例。

您至少需要使其成爲@Scope("session")

0

stopRun在第一次運行到testRun之前被調用,因此該成員是null。這是因爲每個方法調用都發生在一個新的實例上。