Java Runnable Queue
我需要对下面的关键代码进行同行评审。
此类维护一个可运行的objets队列,并确保它们按顺序执行,即在前一个完成后启动一个新的,直到队列中不再有任务为止。
我很确定它确实如此,但我必须绝对确定它的行为是有意的。
非常感谢 !
public final class RunnableQueue { private final ExecutorService m_executorService; private final Queue m_runnables; private final Runnable m_loop; public RunnableQueue(ExecutorService executorService) { m_executorService = executorService; m_runnables = new LinkedList(); 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); } } } } }
编辑
基本上,将使用相同的ThreadPool
实现数百个RunnableQueue
并且每个Runnable
可以在其他Runnable
中添加其他RunnableQueue
。
因此,新的Runnable
将在运行时添加到RunnableQueue
……
您是否有任何理由不使用单线程的固定线程池?
ExecutorService service = Executors.newFixedThreadPool(1);
submit
service
Runnable
s将完全按照您的要求进行服务操作。
明显的问题:为什么在不想并行执行这些线程时使用Runnable
(线程)?
如果想要将队列中的项与其他项并行执行,则可以考虑仅使用一个线程(runnable)按顺序执行队列中的所有命令 :
private Queue queue = initQueue(); public run() { while(!stop) { Command nextCommand = queue.pop(); nextCommand.execute(); } }
Command
是一个只有一个方法的自定义界面。 (注意:这个简单的例子预计队列永远不会是空的)