百步飞剑 盖聂 2018-11-21 07:13 采纳率: 0%
浏览 464

关于java生产者和消费者问题

代码如下,为什么我打断点,断点不进push()方法?

 public class Container {

        //仓库
        private List<Integer> list=new LinkedList<Integer>();

        public static Integer maxSize=10;

        public List<Integer> getList() {
            return list;
        }

        public void setList(List<Integer> list) {
            this.list = list;
        }

        /**
         * 
         * 从仓库中拿
         * @return
         * @see [类、类#方法、类#成员]
         */
        public synchronized Integer pop(){
            synchronized (list) {
                Integer num=null;
                if(!list.isEmpty()){
                    num= list.remove(0);
                    System.out.println("移除了"+num);
                    list.notifyAll();
                }else{
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                return num;
            }
        }

        /**
         * 
         * 推送到仓库中
         * @param num
         * @see [类、类#方法、类#成员]
         */
        public synchronized void push(){
            synchronized (list) {
                Random random=new Random();
                Integer num=random.nextInt(2);
                if(list.size()<maxSize){
                    list.add(num);
                    System.out.println("添加了"+num);
                    list.notifyAll();
                }else{
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }

        public static void main(String[] args) {
            final Container container=new Container();
            Thread consume=new Thread(new Runnable() {
                public void run() {
                    while(true){
                        container.pop();
                    }
                }
            });
            Thread produce=new Thread(new Runnable() {
                public void run() {
                    container.push();
                }
            });
            consume.start();
            produce.start();
        }
}
  • 写回答

1条回答 默认 最新

  • 天涯云海 2018-11-21 07:43
    关注

    删除push和pop方法上的synchronized关键字

    评论

报告相同问题?

悬赏问题

  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图