【发布时间】:2016-08-15 03:02:07
【问题描述】:
我有一个实现可调用接口的类。我想使用 ScheduledExecutorService 接口的 scheduleAtFixedRate 方法为该类安排一个任务。然而 scheduleAtFixedRate 需要一个可运行的对象作为它可以调度的命令。
因此,我需要某种方法来将可调用对象转换为可运行对象。我尝试了简单的强制转换,但这不起作用。
示例代码:
package org.study.threading.executorDemo;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class ScheduledExecutionTest implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("inside the call method");
return null;
}
}
public class ScheduledExecution {
public static void main(String[] args) {
ScheduledExecutorService sec = Executors.newScheduledThreadPool(10);
sec.scheduleAtFixedRate(new ScheduledExecutionTest(), 5, 2, TimeUnit.SECONDS);
}
}
【问题讨论】:
-
implements Callable, Runnable不起作用吗?我以前从未尝试过同时使用这两种方法。 -
Callable的目的是返回一个值。为什么要以固定速率返回要丢弃的值? -
把@PeterLawrey 的评论换一种方式,你想对'Callable`返回的值做什么do?
标签: java multithreading runnable callable scheduledexecutorservice