【问题标题】:How to implementing BlockingQueue with Custom Comparator with ThreadExecutor?如何使用带有 ThreadExecutor 的自定义比较器实现 BlockingQueue?
【发布时间】:2015-08-31 06:26:07
【问题描述】:

我正在尝试根据字符串长度升序运行任务。但是它没有按预期工作。这是我到目前为止尝试过的代码:

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

public class PriorityQueueTest {
    public static void main(String... args) throws InterruptedException {
        BlockingQueue<Runnable> pq = new PriorityBlockingQueue<Runnable>(5,
                new PriorityQueueComparator());
        Runner r1 = new Runner("ABC");
        Runner r2 = new Runner("AB");
        Runner r3 = new Runner("ABCD");

        Runner[] arr = new Runner[] { r1, r2, r3 };

        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 3, 0,
                TimeUnit.SECONDS, pq);

        for (int i = 0; i < arr.length; i++) {
            pool.execute(arr[i]);
        }
        pool.shutdown();

    }
}

class PriorityQueueComparator<T extends Runner> implements Comparator<T> {

    public int compare(Runner o1, Runner o2) {
        if (o1.getName().length() < o2.getName().length()) {
            return 1;
        }
        if (o1.getName().length() > o2.getName().length()) {
            return -1;
        }
        return 0;
    }

}

class Runner implements Runnable {
    private String name;

    public Runner(String sname) {
        this.name = sname;
    }

    public void run() {
        System.out.println(name);
    }

    public String getName() {
        return name;
    }

}

我希望输出是

AB
ABC
ABCD

ABCD
ABC
AB

基于我的客户ComparatorcompareTo() 方法?

我猜自定义比较器没有被调用。

请帮忙。

【问题讨论】:

  • 这可能是因为Runner 对象从不排序,因为队列中一次存储的对象不超过一个。要进行更相关的测试,您应该使任务持续时间更长,减少线程池的容量,以便队列一次存储多个对象。

标签: java multithreading executorservice blockingqueue


【解决方案1】:

PriorityQueue 只对此时队列中的任务进行排序。没有

  • 对已开始的任务进行排序。
  • 对尚未添加的任务进行排序。
  • 如果您有多个线程,请更改任务完成的顺序。

如果您有少量短期任务和多个线程。你不应该期望看到很大的不同。

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    相关资源
    最近更新 更多