【发布时间】:2016-01-22 06:10:32
【问题描述】:
当有一个生产者和一个消费者时,我的代码运行良好。但是,如果我有多个消费者或生产者,他们会得到相同的价值。(我见过很多答案,但它们很复杂,有没有简单的解决方案)。
class QC {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
制片人
class ProducerC implements Runnable {
QC q;
ProducerC(QC q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
}
消费者
class ConsumerC implements Runnable {
QC q;
ConsumerC(QC q) {
this.q = q;
new Thread(this, "Consumer").start();
}
@Override
public void run() {
while(true) {
q.get();
}
}
}
主要
public class CorrectPC {
public static void main(String[] args) {
QC q = new QC();
new ProducerC(q);
new ConsumerC(q);
new ProducerC(q);
System.out.println("Press Control-C to stop.");
}
}
【问题讨论】:
-
结果和预期结果如何?在这里,您有两个生产者,因此单个消费者应该获得每个数字两次(每个生产者一次)。
-
这段代码应该比简单的阻塞队列更简单的度量标准是什么?它更长,未经测试,只处理有用功能的子集(好吧,我想这更简单)。
标签: java multithreading producer-consumer