gpt4 book ai didi

java - 我怎样才能停止一个线程?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:58 24 4
gpt4 key购买 nike

我制作了一个倒计时计时器,“停止”按钮用于停止倒计时并重置文本字段。

class Count implements Runnable {
private Boolean timeToQuit=false;

public void run() {
while(!timeToQuit) {
int h = Integer.parseInt(tHrs.getText());
int m = Integer.parseInt(tMins.getText());
int s = Integer.parseInt(tSec.getText());
while( s>=0 ) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ie){}
if(s == 0) {
m--;
s=60;
if(m == -1) {
h--;
m=59;
tHrs.setText(Integer.toString(h));
}
tMins.setText(Integer.toString(m));
}
s--;
tSec.setText(Integer.toString(s));
}
}
tHrs.setText("0");
tMins.setText("0");
tSec.setText("0");
}

public void stopRunning() {
timeToQuit = true;
}
}

当按下“停止”按钮时,我会调用 stopRunning()。这是行不通的。

另外,我调用 stopRunning() 对吗??

public void actionPerformed(ActionEvent ae) 
{
Count cnt = new Count();
Thread t1 = new Thread(cnt);
Object source = ae.getSource();
if (source == bStart)
{
t1.start();
}
else if (source == bStop)
{
cnt.stopRunning();
}
}

最佳答案

您需要使您的timeToQuit 变量volatile,否则false 的值将被缓存。此外,没有理由将其设为 Boolean - 原语也可以:

private volatile boolean timeToQuit=false;

还需要改变内循环的条件,注意timeToQuit:

while( s>=0 && !timeToQuit) {
...
}

您还可以添加对 interrupt 的调用,但由于您的线程距离检查标志的时间不会超过一秒,因此没有必要这样做。

关于java - 我怎样才能停止一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18933997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com