BlockingQueue初体験
1826 ワード
キューをブロックし、優先順位キューをテストしました.以下はテストコードで、キューで使用し、優先的にチャージしたり、メールを送信したりするときに使用します.
@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;
}
}