优先级队列PriorityQueue介绍

 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+ "]";
    }

    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值