我需要对下面的关键代码进行同行评审。
该类维护一个可运行对象的队列,并确保它们按顺序执行,即在前一个对象完成后开始一个新的任务,直到队列中没有更多任务为止。
我很确定它确实如此,但我必须绝对确定它的行为符合预期。
非常感谢 !
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);
}
}
}
}
}
Edit
基本上会有数百个RunnableQueue
使用相同的实例化ThreadPool
和每个Runnable
执行时可能会添加其他Runnable
其他RunnableQueue
.
So, new Runnable
将被添加到RunnableQueue
当它运行时...
您不使用单个线程的固定线程池有什么原因吗?
ExecutorService service = Executors.newFixedThreadPool(1);
submit
ting Runnable
s to service
由于该服务不在队列中运行,因此将完全按照您的要求进行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)