![](/img/trans.png)
[英]How to return the return value of the Runnable or Callable passed to ScheduledExecutorService.schedule
[英]How to return value with ScheduledExecutorService?
我使用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()));
您应该使用Callable
,它可以返回值而不是Runnable
Callable接口类似于Runnable,因为它们都是为其实例可能由另一个线程执行的类而设计的。 但是,Runnable不会返回结果,也不会抛出已检查的异常。
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取消调度,将很容易。
如果要从doMathForAMinute
返回结果,则根本不需要ScheduledExecutorService。 只需创建一个运行计算的循环,然后运行Thread.sleep()。 使用ScheduledExecutorService的整个想法是释放启动任务的线程等待结果,但在这里你不会释放它。
如果,正如我怀疑的那样,调用doMathForAMinute
的线程是GUI线程,那么这是完全错误的,因为你的gui会卡住并且不会响应一分钟。 相反, doMathForAMinute
应该只启动并行计算,而并行任务本身应该使用runOnUiThread
或其他方式更新UI。
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.