我的理解是,我不需要使用任何方法来对 a 进行排序PriorityQueue
,而只是向其中添加项目并获取项目会使它们保持自然顺序。
队列
public class JobSetQueue extends PriorityBlockingQueue<JobSet> {
public JobSetQueue() {
super(1, new JobSetComparator());
}
}
比较器
我已经通过调试器来验证下面的 getValue() 方法是否返回了最高优先级的预期值,并且返回了 Comparator 期望的正确值。我错了吗? 为了让比较器影响 PriorityQueue 顺序,我需要做些什么吗?
public class JobSetComparator implements Comparator<JobSet> {
@Override
public int compare(JobSet o1, JobSet o2) {
return Integer.compare(o1.getHighestPriority().getValue(), o2.getHighestPriority().getValue());
}
}
优先
public class Priority {
public static final Priority TOP = new Priority("TOP", 1000);
public static final Priority PRIORITY_REMAN = new Priority("PRIORITY_REMAN", 750);
public static final Priority PRIORITY = new Priority("PRIORITY", 500);
public static final Priority STANDARD_REMAN = new Priority("STANDARD_REMAN", 250);
public static final Priority STANDARD = new Priority("STANDARD", 100);
private final String name;
private final int value;
protected Priority(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String toString() {
return getName();
}
}
我的测试:
@Before
public void setUp() {
queue = new JobSetQueue();
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.STANDARD), 1)));
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.PRIORITY_REMAN), 1)));
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.PRIORITY), 1)));
}
@Test
public void testTop() {
queue.add(new JobSet(new JobUnit(new Product(new ProductEntity(), Priority.TOP), 1)));
Assert.assertEquals("Queue priority,", Priority.TOP, queue.poll().getJobUnitList().get(0).getProduct().getPriority());
}