java - 阻塞队列替代synchronized

标签 java

我用下面的阻塞队列替换了以下代码。
为什么我会收到队列已满异常 - 阻塞队列不是应该阻止这种情况发生吗?

    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){}
                }
            }
        }       
    }

阻塞队列等效 -

BlockingQueue<Integer> b = new ArrayBlockingQueue<Integer>(10);
    class Offer implements Runnable{
        Random r=new Random();
        public void run(){
            while(System.currentTimeMillis() < end){
                b.add(r.nextInt());
            }
        }       
    }

    class Take implements Runnable{
        public void run(){
            while(System.currentTimeMillis() < end){
                b.remove(0);
            }
        }       
    }

最佳答案

由于 wait()notify() 是阻塞操作,因此您应该使用 BlockingQueue 中的阻塞操作:put()take()。作为一般建议:永远不要吞下 InterruptedExceptionHere是一篇关于处理 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();
            }
        }
    }
}

关于java - 阻塞队列替代synchronized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43956250/

相关文章:

java - 具有自定义 HTTP 客户端的 WebView

java - 使用 Selenium 将测试结果写入 Excel

java - 根据 HttpServletRequest 参数使 HTML 元素可见/不可见

java - 我已经导入了 org.openqa.selenium.interactions.Actions 但仍然抛出错误 Actions can not parsed to a variable

java - 帧率与采样率

java - 是否可以将数组的某些值复制到另一个数组中,但具有相同的引用?

java - 在 Matisse 中更改组件的类型

java - 我可以使用什么符号表来存储约 5000 万个字符串并进行快速查找,而不会耗尽堆空间?

java - 进化生物 - 使用由我自己创建的复杂类的实例构建的个体创建遗传算法

java - 通过复制构造函数复制对象是否会获得与原始对象相同的实例变量?