本文介绍了Java Runnable Queue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对以下关键代码段进行同行评审。

I need peer reviews of the critical piece of code below.

此类维护一个可运行的objets队列,并确保它们按顺序执行,即启动完成上一个之后的一个新的,直到队列中没有任何任务。

This class maintain a queue of runnable objets, and ensure they are executed sequentially, that is, start one new after the previous one is completed until there is no more task in the queue.

我很确定它确实如此,但我必须绝对确定它表现得很好。

I'm pretty sure it does, but I'm must be absolutely sure it behave as intented.

非常感谢!

public final class RunnableQueue {

    private final ExecutorService m_executorService;
    private final Queue<Runnable> m_runnables;
    private final Runnable m_loop;

    public RunnableQueue(ExecutorService executorService) {
        m_executorService = executorService;
        m_runnables = new LinkedList<Runnable>();

        m_loop = new Runnable() {
            public void run() {

                Runnable l_runnable = current();

                while(l_runnable != null) {
                    l_runnable.run();
                    l_runnable = next();
                }
            }
        };
    }

    private Runnable current() {
        synchronized (m_runnables) {
            return m_runnables.peek();
        }
    }

    private Runnable next() {
        synchronized (m_runnables) {
            m_runnables.remove();
            return m_runnables.peek();
        }
    }

    public void enqueue(Runnable runnable) {
        if(runnable != null) {
            synchronized (m_runnables) {
                m_runnables.add(runnable);
                if(m_runnables.size() == 1) {
                    m_executorService.execute(m_loop);
                }
            }
        }
    }
}

编辑

基本上,将有数百个 RunnableQueue 使用instanciated相同的 ThreadPool 并且每个 Runnable 执行可能会添加其他 Runnable 在其他 RunnableQueue

Basicaly, there will be hundreds of RunnableQueue instanciated using the same ThreadPool and each Runnable executed may add other Runnable in other RunnableQueue.

所以,新的 Runnable 将在运行时添加到 RunnableQueue ...

So, new Runnable will be added to the RunnableQueue while it runs...

推荐答案

任何你不使用固定线程池与单个线程的原因?

Any reason you don't use fixed thread pool with a single thread?

ExecutorService service = Executors.newFixedThreadPool(1);

提交 ting Runnable service 将完全按照您的要求执行服务操作。

submitting Runnables to service will do exactly what you want as the service operates off a queue.

这篇关于Java Runnable Queue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-01 00:57