PriorityBlockingQueue应用
import java.util.concurrent.PriorityBlockingQueue; /** * @author :jiaolian * @date :Created in 2021-02-03 15:44 * @description:priorityBlockingQueue优先级队列测试 * @modified By: * 公众号:叫练 */ public class PriorityBlockingQueueTest { public static void main(String[] args) { m2(); } public static void m2() { PriorityBlockingQueue<Student> priorityBlockingQueue = new PriorityBlockingQueue<>(); priorityBlockingQueue.add(new Student("叫练1",22)); priorityBlockingQueue.add(new Student("叫练2",21)); priorityBlockingQueue.add(new Student("叫练3",23)); while (!priorityBlockingQueue.isEmpty()) { Student student = null; try { student = priorityBlockingQueue.take(); } catch (Int<mark style="color:transparent">来源gaodaimacom搞#代%码网</mark>erruptedException e) { e.printStackTrace(); } System.out.println(student); } } private static class Student implements Comparable<Student> { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Student o) { //从大到小排队 return this.age - o.getAge(); } } }
如上代码:PriorityBlockingQueue是优先级队列,PriorityBlockingQueue队列的元素须要实现Comparable接口,实现队列的排序,上述代码中定义了Student类实现Comparable接口,Student的compareTo接口依照age属性从小到大排队,输入后果如下图所示。PriorityBlockingQueue底层是二叉均衡树的数组构造实现出队和入队。
DelayQueue应用
import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; /** * @author :jiaolian * @date :Created in 2021-02-03 16:28 * @description:提早队列测试 * @modified By: * 公众号:叫练 */ public class DelayQueueTest { public static void main(String[] args) throws InterruptedException { DelayQueue<Student> delayQueue = new DelayQueue<Student>(); delayQueue.add(new Student("叫练1",5)); delayQueue.add(new Student("叫练2",3)); delayQueue.add(new Student("叫练3",6)); while (!delayQueue.isEmpty()) { System.out.println(delayQueue.take()); } } private static class Student implements Delayed { private String name; //触发工夫/秒 private long time; public String getName() { return name; } public long getTime() { return time; } public Student(String name, long time) { this.name = name; this.time = time*1000+System.currentTimeMillis(); } @Override public long getDelay(TimeUnit unit) { //延迟时间小于0就出队列 long aa = time - System.currentTimeMillis(); return aa; } @Override public int compareTo(Delayed o) { //工夫排序,从小到大排列 Student student = (Student) o; return (int)(this.time - student.getTime()); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", time=" + time + '}'; } } }
如上代码:DelayQueue是延时队列,只有到指定工夫的队列才能够出队列,底层应用优先级队列,下面代码定义Student类须要实现Delayed接口同时须要实现getDelay办法和compareTo办法,getDelay办法用于计算出队列工夫,一旦小于0就会出队列;compareTo办法用于按触发工夫从小到大排序。执行程序后,学生“叫练2”3秒后出队列;学生“叫练1”5秒后出队列;学生“叫练3”6秒后出队列。执行后果如下图所示。
总结
明天咱们的内容比较简单。喜爱的请点赞和评论哦!点关注,不迷路,我是叫练【公众号】,边叫边练。期待咱们下次再见!