2014-05-19 77 views
0

我有一個簡單的GUI,其中有兩個按鈕:PrintStop線程:如何中斷該線程外部的線程

當用戶按print時,一個已保存的號碼是連續打印在循環

當用戶按Stop,時,打印停止

我正在處理在單獨的線程中打印數字,因爲我需要線程在再次打印之前睡眠一毫秒。

printBtn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 

       Thread a= new Thread(new Runnable(){ 
        public void run(){ 
         textArea.setText(""); 
         for (int i=0; i<10; i++){ 
          int result= 0; 
          System.out.println(result+"\n"); 
          try { 
           Thread.sleep(1000); 
          } catch (InterruptedException e) { 
           e.printStackTrace(); 
          } 
         } 
        } 
       }); 
       a.start(); 
      } 
     }); 

現在,在停止按鈕的ActionListener,我想第一個線程被中斷或停止。我該怎麼做,因爲它需要從另一個線程中斷?

+0

從另一個線程,爲什麼? – PKlumpp

+0

使用'Timer'或者更好的'ScheduledExectuorService'。在ScheduledFututre上調用Timer或cancel()來調用'cancel()'。除非你知道你在做什麼,並且有充足的理由,否則不要使用原始的'Thread'。 –

+0

@ZOO因爲這個線程只包含了這個線程的run方法內的任何東西。這是一個完全不同的按鈕,具有不同的動作偵聽器。我可以在此線程內實現該按鈕的動作偵聽器嗎?我在這裏錯過了什麼嗎? – Solace

回答

1

如果你的第一個線程不包含線程阻塞操作,你可以例如檢查for -loop中的一個標誌,當你按下「Stop」按鈕時它被設置爲true

public class WriterThread implements Runnable { 

    private volatile boolean stopped = false; 

    public synchronized void stop() { 
     this.stopped = true; 
    } 

    public void run(){ 
      textArea.setText(""); 

      for (int i=0; i<10; i++) { 
        if (this.stopped) { 
          break; 
        } 

        int result= 0; 
        System.out.println(result+"\n"); 

        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 
    } 
} 
+1

'stopped'應聲明爲'volatile'。如果不是,JIT將優化if語句(去掉)。 – PeterMmm

+0

對,我混在一起了。 – Smutje

1

使用AtomicBoolean作爲標誌。這將確保線程安全。

Runnable r= new Runnable(){ 

    private AtomicBoolean stop= new AtomicBoolean(false); 

    public void run(){ 
     for(...){ 

      if(stop.get()){ 
       break; // break the loop 
      } 

      ... 

     } 
    } 

    public stop(){ 
     stop.set(true); 
    } 
} 

Thread a= new Thread(r); 
a.start(); 
r.stop(); 
1
final Thread a= new Thread(new Runnable(){ 
    public void run(){ 
     try { 
      textArea.setText(""); 
      for (int i=0; i<10; i++){ 
       int result= 0; 
       System.out.println(result+"\n"); 
       Thread.sleep(1000); 
      } 
     } catch (InterruptedException e) { 
      // ignore 
     } 
    } 
}); 

printBtn.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 

     a.start(); 
    } 
}); 

stopBtn.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 

     if(a.isAlive()) { 
      a.interrupt(); 
     } 
    } 
});