如何保证ThreadPoolExecutor中的FIFO执行顺序 [英] How to guarantee FIFO execution order in a ThreadPoolExecutor

查看:512
本文介绍了如何保证ThreadPoolExecutor中的FIFO执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用以下代码创建一个ThreadPoolExecutor:

I create a ThreadPoolExecutor with this line of code :

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

然后,我运行了25个任务(T01至T25),所以情况是:

Then, I run 25 tasks (T01 to T25) so the situation is :

  • 当前正在运行5个任务(T01至T05)
  • 20个任务在队列中等待(T06至T25)

当我再放置1个任务(T26)时,由于队列已满,我希望删除较旧的任务(T06)以启动(因为未达到MaxPoolSize),而将新任务(T26)放在队列的结尾.

When I put 1 more task (T26), as the queue is full, I expected that the older task (T06) is removed to be launched (because MaxPoolSize is not reached) and the new task (T26) is placed at the end of the queue.

但是在现实生活中,如果队列"已满并且未达到MaxPoolSize,则会启动最新任务.

But in real life, if Queue is full and MaxPoolSize is not reached, the newest task is started.

所以,我有...

  • 当前正在运行6个任务(T01至T05和T26)
  • 20个任务在队列中等待(T06至T25)

...而不是...

... instead of ...

  • 当前正在运行6个任务(T01至T06)
  • 队列中有20个任务正在等待(T07至T26)

我可以配置ThreadPoolExecutor获得预期的结果吗? 我应该使用其他课程吗?

Can I configure the ThreadPoolExecutor to get the expected result ? Should I use another classes ?

有关信息,请参阅ThreadPoolExecutor源代码的一部分

For information, part of ThreadPoolExecutor source code

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;
}

谢谢

推荐答案

我将使核心大小等于最大值.这就是大多数池的使用方式,我不确定您的情况何时会带来不利影响,但是您会按顺序执行任务.

I would make the core size equal the maximum. This is how most of the pools are used and I am not sure when would be the downside in your case, but you would get the tasks executed in order.

这篇关于如何保证ThreadPoolExecutor中的FIFO执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆