简体   繁体   English

如何使ThreadPoolExecutor使用双端队列?

[英]How can I make a ThreadPoolExecutor use a deque?

I need a thread pool that may receive tasks to be inserted either into the back of the queue (as usual), or into the front of the queue (for priority tasks). 我需要一个线程池,该线程池可能会接收要插入到队列后面(与往常一样)或队列前面(对于优先级任务)的任务。 Tasks should then be executed normally, polled from the head of the queue. 然后,应从队列的头开始,正常执行任务。

I realize this means creating my own ThreadPoolExecutor using a BlockingDeque , but that's not enough... How do I actually tell the thread pool to call the queue's offerFirst method instead of offer ? 我意识到这意味着使用BlockingDeque创建自己的ThreadPoolExecutor ,但这还不够...我实际上如何告诉线程池调用队列的offerFirst方法而不是offer

You need to pass the PriorityBlockingQueue to the ThreadPoolExecutor, probably using this constructor. 您可能需要使用此构造函数,将PriorityBlockingQueue传递给ThreadPoolExecutor。 Added example below of how to initialise the PriorityBlockingQueue with a comparator 下面添加了有关如何使用比较器初始化PriorityBlockingQueue的示例

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

Edit - Example to add a comparator to your priority queue 编辑-将比较器添加到优先级队列的示例

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class PriorityBlockQueueTest {

    private static BlockingQueue<PriorityTask> taskQueue = new PriorityBlockingQueue<>(10,
            new Comparator<PriorityTask>() {
        @Override
        public int compare(PriorityTask o1, PriorityTask o2) {
            return o2.getData() - o1.getData();
        }
    });

    public static void main(String arg[]) {
        taskQueue.add(new PriorityTask(2, 10));
        taskQueue.add(new PriorityTask(1, 11));

        System.out.println(taskQueue);
    }

    private static class PriorityTask implements  Runnable {
        private int priority;
        private int data;
        public PriorityTask(int priority, int data) {
            this.priority = priority;
            this.data = data;
        }

        public int getData() {
            return data;
        }

        public void run() {
            System.out.println("Running something");
        }

        public String toString() {
            return "priority: " + priority + " data: " + data;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM