【问题标题】:No output data at all for Producer/Consumer threading生产者/消费者线程根本没有输出数据
【发布时间】:2017-02-12 20:11:03
【问题描述】:

编辑: 我有一个生产者类,它向 SharedBuffer 类发送一些数据。将此数据添加到限制设置为 100 的 ArrayList 中。将数据添加到所述列表中没有问题,但消费者类无法从列表中获取任何数据。

根本不产生任何输出(没有空值或错误)。

编辑2:添加了将数据放入数组的方法。

SharedBuffer 类:

    static final int RESOURCE_LIMIT = 100;

    private List<String> data = new ArrayList<String>();
//  private boolean done = false;


    public boolean isFull(){
        return data.size() >= RESOURCE_LIMIT;
    }

    public boolean isEmpty(){
        return data.size() <= 0;
    }

    public synchronized void putData(String s){
        while(this.isFull()){
            try{
                wait();
            }catch(InterruptedException e){
                //
                e.printStackTrace();
            }
        }
        data.add(s);
        //size works and there is data in list.
        //System.out.println(data.size() + data.get(0)); 

        public boolean isEmpty(){
            return data.size() <= 0;
        }

        public synchronized String getData(){
            while(this.isEmpty()){
                try{
                    wait();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }

            String s_data = (String)(data.get(0));
            if(s_data != null){
                data.remove(s_data);
                System.out.println(s_data);
            }
            return s_data;
        }

消费类:

    @Override
    public void run() {
        while(true){
            String line = buffer.getData();
            if(line != null){
                System.out.println(line);

                //do stuff with the data.
            }
        }
    }   

【问题讨论】:

  • 您能否更具体地说明您的问题并仅发布相关代码。
  • 我已经编辑了帖子。我希望现在更好。
  • 如何将数据放入缓冲区。
  • 您的isEmpty 方法也必须同步,因为它访问data 字段。
  • 我已经添加了 put 方法,但我怀疑这是问题所在。

标签: java multithreading arraylist bufferedreader producer-consumer


【解决方案1】:

更改您的代码(添加 notyfyAll() 调用)

public synchronized void putData(String s){
    while(this.isFull()){
        try{
            wait();
        }catch(InterruptedException e){
            //
            e.printStackTrace();
        }
    }
    data.add(s);
    notifyAll();
}

public synchronized String getData(){
    while(this.isEmpty()){
        try{
            wait();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }

    String s_data = (String)(data.get(0));
    if(s_data != null){
        data.remove(s_data);
        System.out.println(s_data);
    }
    notifyAll();
    return s_data;
}

您还应该同步isEmpty 和isFull 方法,因为可以访问data。

【讨论】:

  • 啊,我明白了。我从不叫醒消费者。
猜你喜欢
  • 1970-01-01
  • 2018-09-24
  • 2017-02-01
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
相关资源
最近更新 更多