实现说明
全部逻辑都在类 PrintQueue、Job中。
驱动整个流程的是 while (!queue.isEmpty()) 这一个循环。
使用要点
- 跑完文件,输出里会留下标记——
run:。
常见问题
运行「PriorityBlockingQueue 按优先级出队」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 run: 标签标明各步骤。
核心语句
queue.put(new Job("nightly-report", 1));
queue.put(new Job("checkout-retry", 9));
queue.put(new Job("cache-warm", 4));
代码示例
import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;
public class PrintQueue {
record Job(String name, int priority) {}
public static void main(String[] args) throws InterruptedException {
// 优先级数值越大越先出队(comparator 决定堆序)
PriorityBlockingQueue<Job> queue = new PriorityBlockingQueue<>(
11, Comparator.comparingInt(Job::priority).reversed());
queue.put(new Job("nightly-report", 1));
queue.put(new Job("checkout-retry", 9));
queue.put(new Job("cache-warm", 4));
// take 在空队列上阻塞等待;这里元素足够,直接按序取完
while (!queue.isEmpty()) {
System.out.println("run: " + queue.take().name());
}
}
}