我们只需要把放入该队列的对象实现Comparable接口就可以轻松实现线程优先级调度了。
下面写一个简单的demo帮助理解吧。
背景:一个车站,有固定车位,有一个出站口。我们知道车站有快车慢车,长途短途等之分。在此我们统一简化为出站优先级,出站顺序根据站内车优先级别排列。
运行结果:
出站-->当前车信息:种类[2]车牌[粤A21123]优先级[1]
出站-->当前车信息:种类[1]车牌[粤A88888]优先级[2]
出站-->当前车信息:种类[1]车牌[粤AGG892]优先级[4]
出站-->当前车信息:种类[2]车牌[粤A12345]优先级[5]
出站-->当前车信息:种类[2]车牌[粤A66666]优先级[6]
出站-->当前车信息:种类[1]车牌[粤A33333]优先级[7]
出站-->当前车信息:种类[2]车牌[粤AJJ000]优先级[9]
下面写一个简单的demo帮助理解吧。
背景:一个车站,有固定车位,有一个出站口。我们知道车站有快车慢车,长途短途等之分。在此我们统一简化为出站优先级,出站顺序根据站内车优先级别排列。
- import java.util.concurrent.PriorityBlockingQueue;
- public class ThreadPriorityScheduleDemo {
- private static final int MAX_PARKING = 50;
- /**
- * @param args
- */
- public static void main(String[] args) {
- ThreadPriorityScheduleDemo instance = new ThreadPriorityScheduleDemo();
- instance.busEnter(new Bus("粤A12345", 2, 5));
- instance.busEnter(new Bus("粤A88888", 1, 2));
- instance.busEnter(new Bus("粤A66666", 2, 6));
- instance.busEnter(new Bus("粤A33333", 1, 7));
- instance.busEnter(new Bus("粤A21123", 2, 1));
- instance.busEnter(new Bus("粤AGG892", 1, 4));
- instance.busEnter(new Bus("粤AJJ000", 2, 9));
- while(true){
- instance.busQuit();
- }
- }
- private static final PriorityBlockingQueue<Bus> busStation = new PriorityBlockingQueue<Bus>(MAX_PARKING);
- /**
- * 车辆进站
- * @param bus
- */
- private void busEnter(Bus bus){
- // System.out.println("进站-->"+bus.toString());
- if(busStation.size()<MAX_PARKING)
- busStation.add(bus);
- else
- System.out.println("站内车位已满");
- }
- /**
- * 车辆出站
- */
- private void busQuit(){
- try {
- Bus bus = busStation.take();
- System.out.println("出站-->"+bus.toString());
- } catch (InterruptedException e) {
- }
- }
- /**
- * 车实例
- * @author jiangw
- *
- * 2010-3-26
- */
- static class Bus implements Comparable<Bus>{
- private String busNo;
- private Integer busType;
- private Integer level;
- private Bus() {}
- private Bus(String busNo, Integer busType, Integer level) {
- super();
- this.busNo = busNo;
- this.busType = busType;
- this.level = level;
- }
- public String getBusNo() {
- return busNo;
- }
- public void setBusNo(String busNo) {
- this.busNo = busNo;
- }
- public Integer getBusType() {
- return busType;
- }
- public void setBusType(Integer busType) {
- this.busType = busType;
- }
- public Integer getLevel() {
- return level;
- }
- public void setLevel(Integer level) {
- this.level = level;
- }
- @Override
- public int compareTo(Bus o) {
- if(o instanceof Bus){
- return (level>o.level)?1:-1;
- }
- return 0;
- }
- @Override
- public String toString() {
- return "当前车信息:种类["+busType+"]车牌["+busNo+"]优先级["+level+"]";
- }
- }
- }
运行结果:
出站-->当前车信息:种类[2]车牌[粤A21123]优先级[1]
出站-->当前车信息:种类[1]车牌[粤A88888]优先级[2]
出站-->当前车信息:种类[1]车牌[粤AGG892]优先级[4]
出站-->当前车信息:种类[2]车牌[粤A12345]优先级[5]
出站-->当前车信息:种类[2]车牌[粤A66666]优先级[6]
出站-->当前车信息:种类[1]车牌[粤A33333]优先级[7]
出站-->当前车信息:种类[2]车牌[粤AJJ000]优先级[9]