java - 生产者/消费者线程根本没有输出数据

标签 java multithreading arraylist bufferedreader producer-consumer

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

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

编辑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.
            }
        }
    }   

最佳答案

更改您的代码(添加 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;
}

此外,您还应该同步 isEmptyisFull 方法,因为要访问数据

关于java - 生产者/消费者线程根本没有输出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856050/

相关文章:

java - Java中的for-each尝试转换元素类型

java - 将参数从 Activity 传递到 android 中的 fragment 时出错

java - 将矩形图像变形为不规则形状

java - 我只是无法让 fragment 工作

java - 如何在 ReactiveCrudRepository @Tailable 中创建方法

java - Weblogic Server 11g 上的自定义线程

java - Java EE 的长事务时间解决方案?

c - 零线程进程?

java - 为什么在插入 LinkedList 和 ArrayList 时得到关于时间的不同输出

java - 使用 Apache Commons Net FTPClient 从 FTP 服务器循环读取多个文件