为什么没有PriorityBlockingQueue队列根据优先级对元素进行排序

时间:2015-08-27 12:37:41

标签: java concurrency blockingqueue blockingcollection

这是我的代码,代码运行结束不是我的例外。

我认为PriorityBlockingQueue按优先级排序但结尾不是我的预期,谁可以告诉我原因。

 public class TestPriorityQueue {  

    static Random r=new Random(47);  

    public static void main(String args[]) throws InterruptedException{  
        final PriorityBlockingQueue q=new PriorityBlockingQueue();  
        ExecutorService se=Executors.newCachedThreadPool();  
        //execute producer  
        se.execute(new Runnable(){  
            public void run() {  
                int i=0;  
                while(true){  
                    q.put(new PriorityEntity(r.nextInt(10),i++));  
                    try {  
                        TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));  
                    } catch (InterruptedException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }); 

        //execute consumer  
        se.execute(new Runnable(){  
            public void run() {  
                while(true){  
                    try {  
                        System.out.println("take== "+q.take()+" left:== ["+q.toString()+"]");  
                        try {  
                            TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));  
                        } catch (InterruptedException e) {  
                            // TODO Auto-generated catch block  
                            e.printStackTrace();  
                        }  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        });  
        try {  
            TimeUnit.SECONDS.sleep(5);  
        } catch (InterruptedException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        System.out.println("shutdown");  
    }  

}  

class PriorityEntity implements Comparable<PriorityEntity> {  
    private static int count=0;  
    private int id=count++;  
    private int priority;  
    private int index=0;  

    public PriorityEntity(int priority,int index) {  
        this.priority = priority;  
        this.index=index;  
    }  

    public String toString(){  
        return id+"* [index="+index+" priority="+priority+"]";  
    }  


    //数字大,优先级高  
  public int compareTo(PriorityEntity o) {  
      return this.priority < o.priority ? 1  
              : this.priority > o.priority ? -1 : 0;  
  }  
} 

以下是结果,我将非常感谢你的帮助

enter image description here

1 个答案:

答案 0 :(得分:5)

一些观察结果:

  1. 在大多数情况下,队列的大小为1.显然,任何排序顺序都不相关。
  2. 在少数情况下,队列大小可能是两个,并且在这种情况下,输出暗示优先级较低的元素是首选。我强调动词“暗示”因为......
  3. 您的代码没有同步块,因此不会阻止以下操作序列:

    q.take();     // consumer thread
    q.put();      // producer thread
    q.toString(); // consumer thread
    

    q.toString()的合法结果显示的优先级高于采取的优先级。

相关问题