我使用ScheduledExecutorService,希望它每10秒进行一次计算,持续一分钟,在那一分钟结束后,将新值返回给我。如何实现?
例如:如果它接收到数字5,它会增加+1六次,然后在一分钟后返回值11。
目前我的代码如下,但无法正常工作:
例如:如果它接收到数字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()));