PriorityBlockingQueue 优先级队列

发布时间 2023-12-04 17:23:54作者: 亲爱的阿道君
package study;

import lombok.Data;

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityBlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        PriorityBlockingQueue<Student> queue = new PriorityBlockingQueue<>(10, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        queue.put(new Student(1, "tom1"));
        queue.put(new Student(3, "tom3"));
        queue.put(new Student(2, "tom2"));

        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
    }

    @Data
    static
    class Student {
        private int age;
        private String name;

        public Student(int age, String name) {
            this.age = age;
            this.name = name;
        }
    }
}