str*_*con 3 java multithreading countdown
我做了一个倒计时器,一个"停止"按钮假设停止倒计时并重置文本字段.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
您需要创建timeToQuit变量volatile,否则false将缓存值.此外,没有理由这样做Boolean- 一个原始的也可以工作:
private volatile boolean timeToQuit=false;
Run Code Online (Sandbox Code Playgroud)
您还需要更改内循环的条件以注意timeToQuit:
while( s>=0 && !timeToQuit) {
...
}
Run Code Online (Sandbox Code Playgroud)
您也可以添加一个调用interrupt,但由于您的线程永远不会超过检查标志一秒钟,因此没有必要.
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |