问题描述
我有一个要以固定速度运行的任务.但是,每次执行后,我还需要任务的结果.这是我尝试过的:
I have a task that I want to run at a fixed rate. However I also need the result of the task after each execution. Here is what I tried:
任务
class ScheduledWork implements Callable<String>
{
public String call()
{
//do the task and return the result as a String
}
}
否,我尝试使用 ScheduledExecutorService
进行计划.事实证明,您不能以固定的速率安排 Callable
,只能执行 Runnable
.
No I tried to use the ScheduledExecutorService
to scheduled it. Turns out you cannot schedule a Callable
at a fixed rate, only a Runnable
can be done so.
请告知.
推荐答案
使用生产者/消费者模式:使Runnable 将其结果放入 BlockingQueue .有另一个线程 take().
Use a producer/consumer pattern: Have the Runnable put its result on a BlockingQueue. Have another thread take() from the queue.
Take是一个阻塞的调用(即仅在队列中有某些内容时才返回),因此您将在结果可用时立即获得结果.
Take is a blocking call (ie only returns when something is on the queue), so you'll get your results as soon as they're available.
您可以将其与好莱坞模式结合使用,为等待线程提供回调,以便您可用时调用代码.
You could combine this with the hollywood pattern to provide the waiting thread with a callback so your code gets called when something is available.
这篇关于以固定的速率安排可呼叫对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!