小编Jea*_*rez的帖子

如何保证ThreadPoolExecutor中的FIFO执行顺序

我用这行代码创建一个ThreadPoolExecutor:

private ExecutorService executor = new ThreadPoolExecutor(5, 10, 120, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20, true));
Run Code Online (Sandbox Code Playgroud)

然后,我运行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 …
Run Code Online (Sandbox Code Playgroud)

java multithreading fifo

8
推荐指数
1
解决办法
3885
查看次数

标签 统计

fifo ×1

java ×1

multithreading ×1