[英]How to force a while loop execute one runnable at a time.
我正在嘗試制作一個簡單的計時器,每次重復后的時間間隔不均勻。
我開始如下:
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.
}
}
}
};
我的問題是,盡管啟動了前一個方法調用的run(),但當我啟動計時器時,while循環似乎可以執行所有操作。 結果,timeShown TextView立即顯示了此actualSeconds = shortLength * ONE_MINUTE
,並每秒跳過1秒,因為2個可運行對象同時運行。
我想在這里實現順序執行。 最好的方法是什么? 也許實現非匿名子類並每次實例化都會有所幫助?
另外,如果您還有其他建議可以改善我的代碼,我將不勝感激。
您應該看看隊列。
這是一個類似問題的鏈接:
您應該使用Executors.newSingleThreadExecutor()
這是關於執行器的教程:
http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
這也可以幫助您更好地理解Java多線程:
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.