我有一个简单的GUI,其中有两个按钮:Print
和Stop
。线程:如何中断该线程外部的线程
当用户按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,我想第一个线程被中断或停止。我该怎么做,因为它需要从另一个线程中断?
从另一个线程,为什么? – PKlumpp
使用'Timer'或者更好的'ScheduledExectuorService'。在ScheduledFututre上调用Timer或cancel()来调用'cancel()'。除非你知道你在做什么,并且有充足的理由,否则不要使用原始的'Thread'。 –
@ZOO因为这个线程只包含了这个线程的run方法内的任何东西。这是一个完全不同的按钮,具有不同的动作侦听器。我可以在此线程内实现该按钮的动作侦听器吗?我在这里错过了什么吗? – Solace