我正在尝试使用 Thread.sleep() 方法在 while 循环内进行延迟。这是我的代码:
new Thread(new Runnable() {
@Override
public void run() {
z=0;
while (z<45){
z++;
handler.post(new Runnable() {
@Override
public void run() {
time.setText(Integer.toString(45-z));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
这段代码本来可以工作,但突然出现了问题。它开始延迟不到一分钟,总时间为 500 毫秒,总时间小于该时间
最佳答案
相反,如果使用不同的线程、Thread.sleep()、Handler 和 while 循环,您可以仅尝试使用这样的 Handler,
private int timerCount = 0;
private static Handler myHandler = new Handler();
private void runVVRunnable() {
myHandler.postDelayed(runnable, 1000);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
timerCount++;
if ((time == null)) {
return;
}
if (timerCount <= 45) {
time.setText(Integer.toString(timerCount));
runVVRunnable();
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
myHandler.removeCallbacks(runnable);
}
您只需调用runVVRunnable()
,它将执行与 while 循环相同的过程
关于java - while 循环内的延迟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087931/