我使用scheduledexecutorservice,我希望它每10秒计算一分钟,然后在这一分钟后返回新值。我该如何做?
例子:
所以它收到5,它加上+1,6次,然后它应该在一分钟后返回我,值为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()));
最佳答案
您应该使用Callable
来返回值,而不是运行
可调用接口类似于runnable,因为两者都是为其实例可能由另一个线程执行的类设计的。但是,runnable不返回结果,也不能抛出checked异常。
public class ScheduledPrinter implements Callable<String> {
public String call() throws Exception {
return "somethhing";
}
}
然后像下面这样使用它
ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
ScheduledFuture<String> future = scheduler.schedule(
new ScheduledPrinter(), 10, TimeUnit.SECONDS);
System.out.println(future.get());
这是一次计划,因此它将只执行一次,一旦返回get调用,您将需要再次计划它。
但是,在您的情况下,很容易使用一个简单的
AtomicInteger
并调用addAndGet
比较条件到达后返回的值,通过调用cancel取消调度。