【发布时间】: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