阻塞队列以替换synchronized

时间:2017-05-13 17:53:33

标签: java

我用下面的阻塞队列替换了以下代码 为什么我得到队列完全异常 - 是不是阻止队列预期会阻止这种情况?

Main

阻塞等价物 -

    class Offer implements Runnable{
        Random r=new Random();
        public void run(){
            while(System.currentTimeMillis() < end){
                synchronized(b){
                    try{
                        while(b.size()>10){
                            b.wait();
                        }
                        b.add(r.nextInt());
                        b.notify();

                    }catch(InterruptedException x){}
                }
            }
        }       
    }

    class Take implements Runnable{
        public void run(){
            while(System.currentTimeMillis() < end){
                synchronized(b){
                    try{
                        while(b.size()<1){
                            b.wait();
                        }   
                        b.remove(0);
                        b.notify();


                    }catch(InterruptedException x){}
                }
            }
        }       
    }

1 个答案:

答案 0 :(得分:0)

由于wait()notify()是阻止操作,您应该使用BlockingQueueput()take()中的阻止操作。作为一般性建议:永远不会吞下InterruptedException Here是关于处理InterruptedException的好文章。

因此BlockingQueue替换为synchronized应如下所示:

BlockingQueue<Integer> b = new ArrayBlockingQueue<Integer>(10);

class Offer implements Runnable{
    Random r=new Random();
    public void run(){
        while(System.currentTimeMillis() < end){
            try {
                b.put(r.nextInt());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

class Take implements Runnable{
    public void run(){
        while(System.currentTimeMillis() < end){
            try {
                b.take();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
相关问题