我想在每次重复后制作一个时间间隔不均匀的简单计时器。
我从以下开始:
case R.id.start:
timerRuns = true;
startCycle();
break;
循环本身如下:
private void startCycle() {
pomodoroLeft = numPomodoro;
while(pomodoroLeft > 0) {
pomodoroLeft--;
actualSeconds = pomodoroLength * ONE_MINUTE;
setTimeAndRun(actualSeconds);
actualSeconds = shortLength * ONE_MINUTE;
setTimeAndRun(actualSeconds);
}
}
方法调用:
private void setTimeAndRun(long timePeriod) {
runTime = timePeriod;
runnable.run();
}
最后可以自行运行:
private Runnable runnable = new Runnable()
{
public void run() {
if (timerRuns) {
runTime -= ONE_SECOND;
String str = String.format("%1$02d : %2$02d",
TimeUnit.MILLISECONDS.toMinutes(runTime),
TimeUnit.MILLISECONDS.toSeconds(runTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(runTime))
);
timeShown.setText(str);
mHandler.postDelayed(this, 1000);
if(timeShown.getText().toString().contentEquals("00 : 00")) {
stopClock();
//here goes the alarm.
}
}
}
};
我的问题是,当我启动计时器时,循环似乎执行一切尽管
incompliete run()的前一个方法调用。因此,timeShown TextView会立即显示此actualSeconds = shortLength * ONE_MINUTE
并每秒跳过1秒,因为2个runnable同时运行。
我想在这里实现顺序执行。最好的方法是什么?也许实现非匿名子类并每次实例化它会有所帮助?
此外,如果您有任何其他建议可以改善我的代码,我将不胜感激。
答案 0 :(得分:1)
你应该看看队列。
以下是类似问题的链接:
How to implement a queue of runnables
您应该使用Executors.newSingleThreadExecutor()
这是关于执行者的教程:
http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
这里也可以帮助你理解java中更好的多线程:
希望这会有所帮助。