我使用 ScheduledExecutorService,我希望它每 10 秒进行一次计算,持续一分钟,然后在那一分钟后返回新值。我该怎么做?
示例:所以它收到 5 它添加 +1 六次然后它应该在一分钟后返回我的值 11。
我到目前为止但没有工作的是:
package com.example.TaxiCabs;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.*;
public class WorkingWithTimeActivity {
public int myNr;
public WorkingWithTimeActivity(int nr){
myNr = nr;
}
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public int doMathForAMinute() {
final Runnable math = new Runnable() {
public void run() {
myNr++;
}
};
final ScheduledFuture<?> mathHandle =
scheduler.scheduleAtFixedRate(math, 10, 10, SECONDS);
scheduler.schedule(
new Runnable() {
public void run() {
mathHandle.cancel(true);
}
}, 60, SECONDS);
return myNr;
}
}
在我的主要活动中,我希望它在 1 分钟后将我的 txtview 文本更改为 11;
WorkingWithTimeActivity test = new WorkingWithTimeActivity(5);
txtview.setText(String.valueOf(test.doMathForAMinute()));