1

我正在尝试做一个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
}

到目前为止我所拥有的,你看的不是很多

4

2 回答 2

3

PriorityQueue 不为您提供排序的迭代顺序。PriorityQueue 的唯一保证是提取方法(peek/poll/remove)将根据您的比较器返回集合中的最小元素。如果您需要排序的迭代顺序 - 请改用 TreeSet/TreeMap。

于 2013-03-04T01:35:54.017 回答
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);
    }
 }      

}
于 2013-02-17T08:55:18.920 回答