我想做一个简单的应用程序。但我想用按钮停止线程。这段代码不起作用。我看所有的网站都是这样的。我不明白为什么不工作。线程以btnStart. btnStop不工作。我编写了 stopThread() 函数来停止。这该怎么办?任何想法?
private volatile boolean isRunning;
==============
private void stopThread() {
isRunning=false;
Thread.currentThread().interrupt();
}
==============
private final void runThread() {
new Thread() {
public void run() {
while (isRunning) {
try {
Random r = new Random();
islemler[0] = "+";
islemler[1] = "-";
islemler[2] = "*";
islemler[3] = "/";
for (int i = 0; i <10; i++) {
islem1 = islemler[r.nextInt(4)];
islem2 = islemler[r.nextInt(4)];
islem3 = islemler[r.nextInt(4)];
islem4 = islemler[r.nextInt(4)];
txt1.setText("1"+islem1+"1");
txt2.setText("1"+islem2+"1");
txt3.setText("1"+islem3+"1");
txt4.setText("1"+islem4+"1");
Thread.sleep(150);
Thread.sleep(50);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
==============
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isRunning=true;
runThread();
**This part is working**
}
});
==============
btnStop = new JButton("Stop");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopThread();
**But this part is not working. Can you help??**
}
});
九州编程
相关分类