62,614
社区成员
发帖
与我相关
我的任务
分享
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("dog");
pq.add("apple");
pq.add("fox");
pq.add("easy");
pq.add("boy");
//
while(!pq.isEmpty()){
for(String s:pq){
System.out.print(s+" ");
}
System.out.println();
System.out.println("Priority.poll() : "+pq.poll());
}
apple boy fox easy dog
Priority.poll() : apple
boy dog fox easy
Priority.poll() : boy
dog easy fox
Priority.poll() : dog
easy fox
Priority.poll() : easy
fox
Priority.poll() : fox
/**
* @param args
*/
public static void main(String[] args) {
int cnt=0;
PriorityQueue<TaskThread> pQueue=new PriorityQueue<TaskThread>(5,new CopyOfSortUtil());
for(int i=0;i<5;i++){
TaskThread myT=new TaskThread();
myT.start();
pQueue.offer(myT);
}
System.out.println(Arrays.toString(pQueue.toArray()));
try {
while (cnt<5) {
while (!pQueue.isEmpty()) {
Thread.sleep(1000L);
TaskThread taskThread = pQueue.peek();
System.out.println(taskThread.getWeight());
}
cnt++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class SortUtil implements Comparator<MyThread> {
/**
* MAX:按照优先级从大到小排列
* MIN:按照优先级从小到大排列(默认)
*/
public final static int MAX=-1;
public final static int MIN=1;
private int stat=0;
public SortUtil(){}
public SortUtil(int status){
stat=status;
}
public int compare(MyThread fst, MyThread scd) {
int ans = 0;
if (stat==MAX) {//从大到小
if (fst.getWeight()<=scd.getWeight()) {
return 1;
}else {
return -1;
}
}else if(stat==MIN||stat==0) {//从小到大
if (fst.getWeight()>=scd.getWeight()) {
return 1;
}else {
return -1;
}
}else {//模式选择错误
System.out.println("模式选择错误!");
System.exit(-2);
}
return ans;
}
/**
* @param args
*/
public static void main(String[] args) {
//这段main函数里的是刚写的~~还没测~~~~
PriorityQueue<MyThread> pQueue=new PriorityQueue<MyThread>(5,new SortUtil());
for(int i=0;i<5;i++){
MyThread myT=new MyThread();
myT.start();
pQueue.offer(myT);
}
System.out.println(Arrays.toString(pQueue.toArray()));
}
}
public void run() {
Calendar cur;
long n;
try {
while (true) {
cur=Calendar.getInstance();
n=cur.getTimeInMillis()/1000;
if (n%2==0) {
weight--;
}else {
weight++;
}
Thread.sleep(n);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PriorityQueue<MyThread> q = new PriorityQueue<MyThread>(10, new Comparator<MyThread>() {
public int compare(MyThread o1, MyThread o2) {
return o1.weight - o2.weight;
}
});
q.offer(new MyThread(5));
q.offer(new MyThread(7));
q.offer(new MyThread(2));
q.offer(new MyThread(6));
q.offer(new MyThread(8));
System.out.println(Arrays.toString(q.toArray()));
public static class MyThread {
private int weight;
public MyThread(int weight) {
this.weight = weight;
}
public String toString() {
return getClass().getSimpleName() + ":" + weight;
}
}