[英]Multiple Producer consumer in java
當有一個生產者和一個消費者時,我的代碼運行良好。 但是,如果我有一個以上的消費者或生產者,他們將獲得相同的價值(我見過很多答案,但很復雜,有沒有簡單的解決方案)。
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提供的並發集合之一作為生產者和消費者之間的常見聯系點。 您可以從https://docs.oracle.com/javase/tutorial/essential/concurrency/collections.html中找到更多信息。
嘗試這個。
class QC {
int n;
boolean valueSet = false;
synchronized int get() {
while (!valueSet) { // if -> while
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
System.out.println("Got: " + n);
valueSet = false;
notifyAll(); // notify -> notifyAll
return n;
}
synchronized void put(int n) {
while (valueSet) { // if -> while
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notifyAll(); // notify -> notifyAll
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.