2014-05-19 78 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(); 
     } 
    } 
});