通过 executorservice 进行顺序事件处理
我有一个事件队列要处理。线程将事件添加到队列中。
我创建了一个可运行的任务,它在 run
方法中执行处理事件所需的所有操作。
我声明了一个 Executors.newCachedThreadPool(); 并执行每个任务。
public class EventHandler {
private static final ExecutorService handlers = Executors.newCachedThreadPool();
public void handleNextEvent(AnEvent event){
handlers.execute(new Task(evt));
}
public class Task implements Runnable{
@Override
public void run() {
//Event processing
}
}
public AnotherClass{
public void passEvent(AnEvent evt)//This is called by another thread
{
EventHandler.handleNextEvent(evt);
}
}
我的问题是,如果我调用执行器的execute,我的代码将获取下一个事件并通过执行器运行下一个可运行程序。 我的目的是仅在上一个任务结束后才处理队列中的下一个事件。
我如何知道上一个任务是否已完成,以便我知道我可以再次调用handleNextEvent?
由任务更新某些状态字段是个好主意吗?
谢谢
I have an event queue to process. A thread adds events to the queue.
I have created a runnable Task that in the run
method does all which is necessary to process the event.
I have declared an Executors.newCachedThreadPool();
and I execute
each Task.
public class EventHandler {
private static final ExecutorService handlers = Executors.newCachedThreadPool();
public void handleNextEvent(AnEvent event){
handlers.execute(new Task(evt));
}
public class Task implements Runnable{
@Override
public void run() {
//Event processing
}
}
public AnotherClass{
public void passEvent(AnEvent evt)//This is called by another thread
{
EventHandler.handleNextEvent(evt);
}
}
My problem is that if I call execute
of the executor, my code will get the next event and run next runnable via the executor.
My purpose is to process next event from queue only after previous task has ended.
How would I know that the previous task has finished or not so that I know I can call handleNextEvent again?
Is having some status field updated by the Task a good idea?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Executors.newCachedThreadPool()
将根据需要创建新线程,因此这不是您想要的。您需要像 Executors.newSingleThreadExecutor() 这样的东西,它将一次处理一个事件,并将其余事件排队。请参阅 javadoc:
Executors.newCachedThreadPool()
will create new threads on demand, so it's not what you want. You want something likeExecutors.newSingleThreadExecutor()
, which will process the events one at a time, and queue up the rest.See javadoc:
我认为
Executors.newSingleThreadExecutor()
和submit()
方法可以解决您的问题:http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent /ExecutorService.htmlI think
Executors.newSingleThreadExecutor()
and thesubmit()
Method are the solution to your problem: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html