gpt4 book ai didi

java - 如何通过 ThreadExecutor 实现带有自定义比较器的 BlockingQueue?

转载 作者:行者123 更新时间:2023-12-01 11:11:28 26 4
gpt4 key购买 nike

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

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()方法?

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

请帮忙。

最佳答案

PriorityQueue 仅对当时队列中的任务进行排序。事实并非如此

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

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

关于java - 如何通过 ThreadExecutor 实现带有自定义比较器的 BlockingQueue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32305087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com