通过执行器进行顺序事件处理 [英] sequential event processing via executorservice

查看:112
本文介绍了通过执行器进行顺序事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件队列来处理。一个线程将事件添加到队列中。

我已经创建了一个可运行的任务,在运行方法中,所有这些都是处理事件所必需的。 br>
我已经声明一个 Executors.newCachedThreadPool(); 和I 执行每个任务。

  public class EventHandler {

private static final ExecutorService handlers = Executors.newCachedThreadPool();

public void handleNextEvent(AnEvent event){

handlers.execute(new Task(evt));

}


public class任务实现Runnable {

@Override
public void run(){
//事件处理
}
}

public AnotherClass {
public void passEvent(AnEvent evt)//这是另一个线程调用
{
EventHandler.handleNextEvent(evt);

}
}

我的问题是,如果我打电话执行者执行执行,我的代码将获得下一个事件,并通过执行程序运行下一个runnable。
我的目的是在上一个任务结束后才从队列中处理下一个事件。

我如何知道先前的任务已经完成,以至于我知道我可以再次调用handleNextEvent? br>
有一些状态字段被Task更新了一个好主意?



谢谢

解决方案

Executors.newCachedThreadPool()将根据需要创建新线程,所以不是你想要的。你想要一些类似 Executors.newSingleThreadExecutor()的东西,这将一次处理一个事件,并排队休息。



请参阅 javadoc


创建一个使用从无界队列运行的单个工作线程的执行程序。 (请注意,如果这个单个线程由于在关闭之前的执行过程中发生故障而终止,则如果需要执行后续任务,则新的线程将占用它。)任务保证顺序执行,并且不超过一个任务将被激活在任何给定的时间。



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

解决方案

Executors.newCachedThreadPool() will create new threads on demand, so it's not what you want. You want something like Executors.newSingleThreadExecutor(), which will process the events one at a time, and queue up the rest.

See javadoc:

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.

这篇关于通过执行器进行顺序事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆