首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java迭代优先级队列

问Java迭代优先级队列
EN

Stack Overflow用户
提问于 2013-02-17 01:34:07
回答 2查看 4.9K关注 0票数 1

我正在尝试执行一个while循环,它将遍历一个java优先级队列,并在队列日期的顶部读取。一是它有日期值,查看队列的其余部分,看看这个日期是否在其他地方使用,如果是,则将这些元素临时添加到它们自己的队列中,这样我就可以调用不同的比较器方法来对它们进行排序。

代码语言:javascript
复制
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
}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-17 16:55:19

代码语言:javascript
复制
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);
    }
 }      

}
票数 1
EN

Stack Overflow用户

发布于 2013-03-04 09:35:54

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14913106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档