我想制作一个简单的应用程序。但我想用按钮停止线程。这段代码不起作用。我看所有的网站都是这样的。我不明白为什么不工作。
线程以 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??**
}
});
最佳答案
问题
您有两个打开的线程,如果您为用户界面留出一个线程,则可能是三个。
第一个线程是程序启动的线程,第二个线程是创建随机对象和 for 循环的线程。当您调用“停止线程”时,您是从主线程或用户界面的第三个线程执行此操作。
这意味着
Thread.currentThread().interrupt();
没有关闭正确的线程。
解决方案
有关此问题的解决方案,请查看此 GeeksForGeeks文章建议将线程存储为变量,然后您可以可靠地调用它的中断方法。
关于java - 使用 Jbutton 停止线程 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58052743/