2014-01-16 147 views
1
public class Threadsample implements ActionListener { 
HelloRunner hr = new HelloRunner(); 
Thread tr1 = new Thread(hr, "ThreadOne"); 
public void actionPerformed(ActionEvent ae) 
    { 

     Object source = ae.getSource(); 
     if (source == b2){ 
      hr.stopRunning(); 
     } 
     if (source== b1){ 

      tr1.start(); 
     } 
    } 


    public class HelloRunner implements Runnable 
    { 
     private volatile boolean timeToQuit=false; 
     int i = 0; 
     public void run(){ 
      while (! timeToQuit){ 
        System.Out.Println(i); 
        i++ 
      } 
     } 
     public void stopRunning() { 
      timeToQuit=true; 
      } 
    } 
} 

如何停止正在運行的線程?停止正在運行的線程

+1

你的邏輯有什麼問題? –

+0

@AniketThakur線程不會停止 –

回答

1

線程中斷是要走的路:

// computingThread computing here 
    while (!Thread.currentThread.isInterrupted()){ 
     System.Out.Println(i); 
     i++; 
    } 


//.... in other part of your program, your main thread for instance:  
    public void stopComptuterThread() { 
     computingThread.interrupt(); // assuming computingThread reference reachable 
    } 

事實上,有些人會用Thread.stop()方法.. =>這裏就是爲什麼它會是非常糟糕:https://www.securecoding.cert.org/confluence/display/java/THI05-J.+Do+not+use+Thread.stop()+to+terminate+threads

0

您的代碼將會執行。你可以使用內建的中斷方法,它大部分都是一樣的,但如果它睡眠/等待,它也會喚醒帶有InterruptedException的線程。很高興知道,Java不允許以「困難的方式」停止線程(除了在線程上使用.stop()方法,這已被棄用)。

所以過程中,一般情況下,看起來如下:

  • 用戶請求線程停止,通過設置標誌(你的情況),或者通過調用.interrupt()方法,它設置標誌。中斷()並「震動」線程,以便在睡眠/等待時醒來。

  • 它的線程可以阻止它的執行。如果你沒有實現一些邏輯處理中斷標誌,那麼線程無法對外部線程做出反應,試圖中斷它,並在JVM結束它的執行後死亡。

+0

但我的代碼不起作用 –

+0

你確定,它是線程問題嗎?您是否檢查過,如果.actionPerformed實際調用.stopRunning方法? 無論如何,請嘗試下面的代碼示例。它工作100% - 檢查自己: –

0

你確定這是線程問題嗎?您是否檢查過,如果.actionPerformed實際調用.stopRunning方法?

無論如何,請嘗試下面的代碼示例。它適用於100%。

class HelloRunner implements Runnable { 
    private volatile boolean timeToQuit = false; 
    int i = 0; 

    public void run() { 
     while (!timeToQuit) { 
      System.out.println(i); 
      i++; 
     } 
    } 

    public void stopRunning() { 
     timeToQuit = true; 
    } 
} 

public class MainRunner { 
    public static void main(String[] args) throws InterruptedException { 
     HelloRunner hr = new HelloRunner(); 
     Thread tr1 = new Thread(hr, "ThreadOne"); 

     tr1.start(); 
     Thread.sleep(100); 
     hr.stopRunning(); 
    } 
}