JAVA并发编程随笔【一】PriorityBlockingQueue优先级队列

来源:互联网 发布:cmd中如何测试80端口 编辑:程序博客网 时间:2024/05/20 06:39

一、优先级队列PriorityBlockingQueue必须是实现Comparable接口,队列通过这个接口的compare方法确定对象的priority。当前和其他对象比较,如果compare方法返回负数,那么在队列里面的优先级就比较搞


    比较规则:当前对象和其他对象做比较,当前优先级大就返回-1,优先级小就返回1


二、优先级队列是一个基于堆的无界并发安全的优先级队列。


三、优先级队列不允许null值,不允许未实现Comparable接口的对象。


四、优先级中传入的实体对象


package framework.yaomy.example;


/**
 * @Description:TODO
 * @version 1.0
 * @since JDK1.7
 * @author yaomingyang
 * @company xxxxxxxxxxxxxx
 * @copyright (c) 2017 yaomy Co'Ltd Inc. All rights reserved.
 * @date 2017年8月27日 上午10:33:48
 */
public class User implements Comparable<User>{

    private Integer priority;
    private String username;
    
    public Integer getPriority() {
        return priority;
    }

    public void setPriority(Integer priority) {
        this.priority = priority;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    /**
     *
     * @Description:当前对象和其他对象做比较,当前优先级大就返回-1,优先级小就返回1
     * 值越小优先级越高
     * @param TODO
     * @author yaomingyang
     * @date 2017年8月27日 上午11:28:10
     */
    @Override
    public int compareTo(User user) {
//        System.out.println("比较结果"+this.priority.compareTo(user.getPriority()));
        return this.priority.compareTo(user.getPriority());
    }
}


五、测试优先级队列


public class PriorityBlockQueueDemo {

    public static void main(String[] args) {
        PriorityBlockingQueue<User> queue = new PriorityBlockingQueue<User>();
        for(int i=0; i<12; i++){
            User user = new User();
            int max=20;
            int min=10;
            Random random = new Random();

            int n = random.nextInt(max)%(max-min+1) + min;

            user.setPriority(n);
            user.setUsername("李艳第"+i+"天");
            
            queue.add(user);
        }
        
        for(int i=0; i<12; i++){
            User u = queue.poll();
            System.out.println("优先级是:"+u.getPriority()+","+u.getUsername());
        }
    }
}


输出结果:

    优先级是:10,李艳第0天
    优先级是:10,李艳第3天
    优先级是:10,李艳第7天
    优先级是:10,李艳第10天
    优先级是:10,李艳第6天
    优先级是:11,李艳第1天
    优先级是:11,李艳第5天
    优先级是:13,李艳第9天
    优先级是:15,李艳第11天
    优先级是:16,李艳第4天
    优先级是:17,李艳第2天
    优先级是:17,李艳第8天


原创粉丝点击