如何保证ThreadPoolExecutor中的FIFO执行顺序
我用这行代码创建一个ThreadPoolExecutor:
private ExecutorService executor = new ThreadPoolExecutor(5, 10, 120, TimeUnit.SECONDS, new ArrayBlockingQueue(20, true));
然后,我运行25个任务(T01到T25),所以情况是:
- 当前正在运行的5个任务(T01到T05)
- 在队列中等待的20个任务(T06到T25)
当我再添加1个任务(T26)时,当队列已满时,我预计将删除旧任务(T06)以启动(因为未达到MaxPoolSize)并且新任务(T26)被放置在末尾队列。
但在现实生活中,如果Queue已满并且未达到MaxPoolSize,则启动最新任务。
所以我有 …
- 当前正在运行的6个任务(T01到T05和T26)
- 在队列中等待的20个任务(T06到T25)
… 代替 …
- 当前正在运行的6个任务(T01到T06)
- 在队列中等待的20个任务(T07到T26)
我可以配置ThreadPoolExecutor来获得预期的结果吗? 我应该使用其他课吗?
有关信息,部分ThreadPoolExecutor源代码
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) { if (runState == RUNNING && workQueue.offer(command)) { if (runState != RUNNING || poolSize == 0) ensureQueuedTaskHandled(command); } else if (!addIfUnderMaximumPoolSize(command)) reject(command); // is shutdown or saturated } } private boolean addIfUnderMaximumPoolSize(Runnable firstTask) { Thread t = null; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { if (poolSize < maximumPoolSize && runState == RUNNING) t = addThread(firstTask); } finally { mainLock.unlock(); } if (t == null) return false; t.start(); return true; }
谢谢
我会使核心大小等于最大值。 这就是大多数池的使用方式,我不确定在你的情况下何时会出现缺点,但你会按顺序执行任务。