scheduleWithFixedDelay仅在调用get()方法时运行

时间:2011-07-18 08:42:03

标签: java concurrency

我正在使用以下代码创建ScheduledExecutorService:

ScheduledExecutorService schedExe = Executors.newSingleThreadScheduledExecutor();

我这样称呼它:

ScheduledFuture<?> sf = schedExe.scheduleWithFixedDelay(new RequestScheduler(), 1, 1, TimeUnit.SECONDS);

RequestScheduler()类用于测试目的是Runnable的一个简单实现:

public class RequestScheduler implements Runnable {
public void run() {
    System.out.println("$$$$RequestScheduler running");

}
 }

当我调用scheduleWithFixedDelay时,没有运行代码。如果我引用它运行的调用返回的ScheduledFuture的get()方法 知道为什么会这样吗?我是否需要在ScheduledExecutorService上调用get()? ScheduledExecutorService的创建是在本地方法中(它之前是类级别,但我移动了它)。这是从main调用的完整方法:

    public void pollDatabase(long databasePoll, String tbHost, int tbPort, int maxPool) throws IllegalAccessException, InstantiationException, ClassNotFoundException{

    if(logger.isInfoEnabled()){
        logger.log(Level.INFO, String.format(Messages.CREATED_SCHEDULER, new Date().toString(),databasePoll,maxPool,tbHost,tbPort) );
    }
    ScheduledExecutorService schedExe = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> sf = schedExe.scheduleWithFixedDelay(new RequestScheduler(), 1, 1, TimeUnit.SECONDS);
    try {
        System.out.println(sf.get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println("-call to executor has been made");
}

感谢阅读。

0 个答案:

没有答案