我想模拟以下情况:多个使用者,生产者线程正在将某些数据修改为
BlockingQueue<String> q1 = new SynchronousQueue<String>();
BlockingQueue<String> q2 = new SynchronousQueue<String>();
Producer dataProducer = new Producer(q1); // publish to q1
Filter1 filter1 = new Filter1(q1, q2); // read from q1, publish to q2
Filter2 filter2 = new Filter2(q2); // read from q2
new Thread(dataProducer, "Producer-Thread").start();
new Thread(filter1, "Filter1-Thread").start();
new Thread(filter2, "Filter2-Thread").start();
public void run() {
try {
while (true) {
this.q.put(saySomething());
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public String saySomething() {
return "Something";
}
public void run() {
try {
while (true) {
consume(qIn.take());
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
private void consume(String take) {
//Modify data according to some rules
String newData = take.replace("m", "-");
produce(newData);
}
private void produce(String newData) {
// put new data in queue out
qOut.add(newData); // <-- Stacktrace points here
}
public void run() {
try {
while (true) {
consume(qIn.take());
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
private void consume(String s) {
System.out.println("Something became: " + s);
}
因此,回顾一下:生产者将某些内容放入队列中,从中读取过滤器1。它修改数据并将其发布到过滤器2读取的另一个队列中。过滤器2打印最终数据。
这段代码失败了
Exception in thread "Thread-2" java.lang.IllegalStateException: Queue full
你能帮我理解为什么吗?
您应该使用put()
而不是add()
SynchronousQueue始终是满空的,没有深度。put()将告诉队列挂起该线程,直到有另一个线程将元素移出队列。
add()
仅当有线程在等待时,该方法才会成功;如果没有线程在等待,您将获得“队列已满”异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句