Java Runnable Queue

Nic*_*uet 3 java multithreading

我需要对下面的关键代码进行同行评审.

此类维护一个可运行的objets队列,并确保它们按顺序执行,即在前一个完成后启动一个新的,直到队列中没有其他任务为止.

我很确定它确实如此,但我必须绝对确定它的行为是有意的.

非常感谢 !

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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

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

因此,新的Runnable将被添加到RunnableQueue运行时...

Qwe*_*rky 10

您是否有任何理由不使用单线程的固定线程池?

ExecutorService service = Executors.newFixedThreadPool(1);
Run Code Online (Sandbox Code Playgroud)

submitRunnables到service会做你想要什么作为服务工作过的队列.


And*_*s_D 8

明显的问题:为什么在Runnable不想并行执行这些线程时使用s(线程)?

如果想要将队列中的与其他并行执行,则可以考虑仅使用一个线程(runnable)按顺序执行队列中的所有命令:

private Queue<Command> queue = initQueue();

public run() {
  while(!stop) {
    Command nextCommand = queue.pop();
    nextCommand.execute();
  }
}
Run Code Online (Sandbox Code Playgroud)

Command是一个只有一个方法的自定义界面.(注意:这个简单的例子预计队列永远不会是空的)