我正在尝试执行一个while循环,它将遍历java优先级队列并在队列日期之前读取。一个具有日期值,查看队列的其余部分以查看此日期是否在其他地方使用,如果是这样,则将这些元素临时添加到它们自己的队列中,这样我就可以调用不同的比较器方法对它们进行排序。
public JobRequest closestDeadlineJob(int freeCPUS) {
// find top job to determine if other jobs for date need to be considered
JobRequest nextJob = scheduledJobs.peek(); // return top most job
// what is it's date?
Date currentDate = nextJob.getConvertedDeadlineDate();
JobPriorityQueue schedulerPriorityQueue = new JobPriorityQueue();
schedulerPriorityQueue.addJob( nextJob );
while(true) {
}
// this is the item at the top of the PRIORTY JOB queue to return
// remove that item from scheduledJobs
// return null; // replace with to the one you want to return
}
到目前为止,我所看到的并不多,
答案 0 :(得分:3)
PriorityQueue不为您提供排序的迭代顺序。 PriorityQueue的唯一保证是提取方法(peek / poll / remove)将根据您的Comparator返回集合中的最小元素。如果需要排序的迭代顺序 - 请改用TreeSet / TreeMap。
答案 1 :(得分:1)
import java.util.Date;
import java.util.Comparator;
import java.util.PriorityQueue;
class Job implements Runnable{
Priority priority;
Date dateOccurance;
public Job(Priority priority, Date occurance){
this.priority = priority;
this.dateOccurance = occurance;
}
public void run(){
//Job execution
System.out.println("executed");
}
}
enum Priority {
High,
Medium,
Low
}
class JobComparator implements Comparator<Job> {
@Override
public int compare(Job j1, Job j2) {
if(j1.priority.ordinal() > j2.priority.ordinal()) {
return 1;
} else if (j1.priority == j2.priority) {
if(j1.dateOccurance.after(j2.dateOccurance)) {
return 1;
} else if (j1.dateOccurance.before(j2.dateOccurance)) {
return -1;
} else {
return 0;
}
}
return -1;
}
}
public class PriorityQueueTest {
public static void main(String[] args) throws InterruptedException {
Date d = new Date();
Job job1 = new Job(Priority.High, d);
Job job2 = new Job(Priority.High, d);
Job job3 = new Job(Priority.Medium, d);
Job job4 = new Job(Priority.Low, d);
Thread.sleep(2000);
Date l = new Date();
Job job5 = new Job(Priority.Low, l);
Comparator<Job> jComp = new JobComparator();
PriorityQueue<Job> queue =
new PriorityQueue<Job>(10, jComp);
queue.add(job4);
queue.add(job3);
queue.add(job1);
queue.add(job2);
queue.add(job5);
while (queue.size() != 0)
{
Job j = queue.remove();
System.out.println(j.priority +" "+j.dateOccurance);
}
}
}