2013-12-08 31 views
0
private void stopThread() { 
    thread1.canRun(false); 
} 

private void createThread() { 
    thread1.stopThread(); 
    thread1.canRun(true); 
    thread1 = new Thread(thread1); 
    t.start(); 

} 

我只有一個按鈕。 當我點擊按鈕,我執行的線程數爲n號 當我再次單擊按鈕時,最後一個線程應該停止並創建一個新線程。使用相同變量的兩個線程

的問題是,當我創建第二個線程似乎是最後一個犯規站,既保持運行

@Override 
    public void run() { 
    try { 
     for (int i = 0; i <= TimeOut && canRun; i++) { 
      System.out.println(i); 
      Thread.sleep(1000); 

      } 

     } 

    private volatile boolean canRun; 

回答

0

問題可能是在這些線路:

thread1.stopThread(); // <-- sets canRun to false 
thread1.canRun(true); // <-- sets canRun to back to true 

你也可以初始化canRun與真實,這將意味着該線程是可運行在它的初始狀態:

private volatile boolean canRun = true; 
+0

我怎麼能停止最後一個線程運行then_ – AlanRubinoff

+0

從你的代碼片段看起來你的'canRun(true)'退回了'thread1.stopThread()'。所以你可以嘗試刪除這一行。 –

+0

你也可以用true來初始化canRun,看看我的更新。 –

相關問題