时间表和可赎回

时间:2011-10-15 13:26:23

标签: java android

我正在尝试在主活动中使用ScheduledExecutorService,其中有一些用户界面控件。在某些情况下,我希望将其中一个调用的方法延迟一秒:

ScheduledExecutorService scheduledExecutorService =
     Executors.newScheduledThreadPool(5);

ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable() {
 public Object call() throws Exception {
  stopSomething();
 }
},
1,
TimeUnit.SECONDS);

try {
 scheduledFuture.get();
} catch (InterruptedException e) {
 e.printStackTrace();
} catch (ExecutionException e) {
 e.printStackTrace();
}

scheduledExecutorService.shutdown();            

这样一段代码可以在程序的另一部分工作,所以我知道这个解决方案的大纲至少在那里起作用。但是在主要活动和我尝试过的程序的其他部分(我实际上可以使用它)中,Eclipse一直在发现错误:

ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable(){  public Object call()抛出异常{

如果编译错误不在Object call() throws Exception,它就在schedule(new Callable()上,就像现在一样。

计划中的红线是“ScheduledExecutorService类型中的方法计划(Runnable,long,TimeUnit)不适用于参数(new Callable(){},int,TimeUnit”“

Callable下的红线是“Callable无法解析为类型”

(也许.schedule(Runnable任务,长延迟,TimeUnit timeunit)是一个更好的方法在这里使用?如果是这样,什么会导致错误“ScheduledExecutorService类型中的方法调度(Runnable,long,TimeUnit)是不适用于参数(new Callable(){},int,TimeUnit)“?这需要什么?它将如何组成?”

2 个答案:

答案 0 :(得分:2)

您正在使用的Callable的返回类型是Object,但您没有返回任何内容

Callable callable = new Callable() {
 public Object call() throws Exception {
  stopSomething();
  // missing return statement
 };

如果您不需要返回任何内容,并且不抛出任何已检查的Exception,您可以使用:

Runnable runnable = new Runnable() {
 public void run() {
  stopSomething();
 };

答案 1 :(得分:0)

即使线程是旧的,这个答案也可以作为参考。

调度程序的签名需要java.util.concurrent.TimeUnit,但TimeUnit也是其他类的名称,如com.ibm.icu.util.TimeUnit或com.ibm.icu.impl.duration.TimeUnit

只需检查您是否从java.util.concurrent包中导入了该文件。

相关问题