优先级队列PriorityQueue介绍

来源:互联网 发布:华为软件研发面试题 编辑:程序博客网 时间:2024/06/07 02:32
 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.lyzx.day01;

import java.sql.Time;
import java.util.PriorityQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Queue
 */
public class T3 {
    
    public static void main(String[] args) throws InterruptedException {
        f2();
    }
    
    /**
     * 测试优先级队列
     * 优先级队列按照元素的优先级做一个插队插入操作
     */
    public static void f1(){
        PriorityQueue<ET> pq = new PriorityQueue<ET>();
        int SIZE =10;
        CountDownLatch latch = new CountDownLatch(SIZE);
        
        for(int i=0;i<SIZE;i++){
            pq.add( new ET(i,latch));
        }
        
        for(int i=0;i<10;i++){
            System.out.println(pq.poll());
        }
        
        try {
            latch.await();
        } catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    
    /**
     * 阻塞优先级队列
     * 按照元素的优先级做一个插队插入操作
     * 并支持阻塞操作,支持在一定的时间范围取出,如果在超时时间内没有
     * 取出元素就返回null
     * @throws InterruptedException
     */
    public static void f2() throws InterruptedException{        
        PriorityBlockingQueue<ET> pbq = new PriorityBlockingQueue<ET>();
        int SIZE=5;
        for(int i=0;i<SIZE;i++){
            pbq.add( new ET(i));
        }

        for(int i=0;i<SIZE+2;i++){
            ET e = pbq.poll(2,TimeUnit.SECONDS);
            System.out.println(e);
        }
    }
}

class ET implements Comparable<ET>{
    private int priority;
    private CountDownLatch latch;
    
    
    public ET(int priority,CountDownLatch latch){
        this.priority=priority;
        this.latch = latch;
    }

    public ET(int priority){
        this.priority=priority;
    }
    
    @Override
    public int compareTo(ET o){
        if(this.priority > o.priority) return -1;
        if(this.priority < o.priority) return 1;
        return 0;
    }

    @Override
    public String toString() {
        if(null != latch){
            latch.countDown();
        }
        return "ET [priority="+priority+"]";
    }

    
}