本文介绍了如何在java中使用ScheduledExecutorService以固定的时间间隔调用Callable实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ScheduledExecutorService具有scheduleAtFixedRate(Runnable命令,long initialDelay,long period,TimeUnit单元)等方法,可以固定的时间间隔调用Runnable类。我希望我的Thread在执行后返回一些值。所以我实现了Callable接口。我找不到一个等效的方法来定期调用我的Callable类。有没有其他方法来实现这个?如果这不是Java提供的功能,那么该决定背后的理性是什么?请告诉我。谢谢。

ScheduledExecutorService has methods like scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit) to invoke Runnable classes at fixed intervals. I want my Thread to return some value after execution. So I implemented Callable interface. I could not find an equivalent method for invoking my Callable class at regular interval. Is there any other way to implement this? If this is functionality is not provided by Java, what is the rational behind that decision? Please let me know. Thanks.

推荐答案

您无法安排 Callable 定期执行目前还不清楚如何从这样的执行返回结果。

You can't schedule Callable for periodic execution since it's unclear how to return a result from such an execution.

如果你有自己的方法来返回结果(例如,将结果放入队列中),你可以将 Callable 包装到 Runnable 中并实施您的方法:

If you have your own approach to returning the result (for example, placing a result into a queue), you can wrap Callable into Runnable and implement your approach:

final BlockingQueue<Result> q = new ArrayBlockingQueue<Result>();
final Callable<Result> action = ...;

s.scheduleAtFixedRate(new Runnable() {
    public void run() {
        q.put(action.call());
    }
}, ...);

这篇关于如何在java中使用ScheduledExecutorService以固定的时间间隔调用Callable实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 10:01