BlockingQueue初体验


阻塞队列,测试了下优先级队列,以下是测试代码,在队列中用以,优先充值或者发送短信的时候使用。

@Test
    public void testPriorityBlockingQueue() throws InterruptedException {
        StudentComparator studentComparator = new StudentComparator();
        BlockingQueue<Student> blockingQueue = new PriorityBlockingQueue<Student> (10,studentComparator);
        Student student1 = new Student();
        student1.setId(1);
        student1.setName("学生1");
        Student student2 = new Student();
        student2.setId(3);
        student2.setName("学生3");
        Student student3 = new Student();
        student3.setId(2);
        student3.setName("学生2");
        blockingQueue.offer(student1);
        blockingQueue.offer(student2);
        blockingQueue.offer(student3);
        while(true){
            Student student= blockingQueue.take();
            System.out.println(student);
        }

    }

    class Student {
        private int id;
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    class StudentComparator implements Comparator<Student>{

        @Override
        public int compare(Student o1, Student o2) {
            if(o1.getId()<=o2.getId()){
                return 1;
            }
            return -1;
        }
    }



你可能感兴趣的:(BlockingQueue初体验)