java - 通过 executorservice 进行顺序事件处理

标签 java multithreading event-handling queue 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?
由任务更新某些状态字段是个好主意吗?

谢谢

最佳答案

Executors.newCachedThreadPool() 将根据需要创建新线程,因此这不是您想要的。您需要类似 Executors.newSingleThreadExecutor() 的东西,它将一次处理一个事件,并将其余事件排队。

参见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.

关于java - 通过 executorservice 进行顺序事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4104420/

相关文章:

java - 评估 fcl 文件时出现异常

c# - 在 WinForms 中保持对控件的全局引用以访问 GUI 线程

c# - 如何从另一个处理程序调用按钮单击事件处理程序? (C# )

c# - 哪个结构更好,将事件处理程序作为参数传递,或监听事件触发?

java - 如何在java spring REST上返回由对象包装的数组字节

java - 从命令行运行程序时找不到类

java - MongoDB:java中的提示索引

c - OpenMP 如何处理 C 中的数组?

c++ - 将多个参数传递给 _beginThreadEx

python - vlc python 绑定(bind) - 如何接收键盘输入?