这是否被认为是 Producer , Consumer Scenario 中的错误?
这是我的 Producer 类。
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Producer extends CommonClass implements Runnable {
private SyncronizedStack stack;
private int producerNum;
Producer(PriorityBlockingQueue<Character> queue) {
this.queue = queue;
}
public void run() {
char ch;
for (ch = 'a'; ch <= 'f'; ch++) {
queue.add(ch);
System.out.println("Producer" + producerNum + "produced :" + ch);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
这是我的消费类
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Consumer extends CommonClass implements Runnable {
private int consumerNum;
Consumer(PriorityBlockingQueue<Character> queue) {
this.queue = queue;
}
public void run() {
char c;
for (int i = 0; i < 7; i++) {
try {
c = queue.take();
System.out.println("Consumer" + consumerNum + "consumed:" + c);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
这是我的 CommonClass
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class CommonClass {
PriorityBlockingQueue<Character> queue = null;
}
这是我的客户程序
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class SyncTest {
public static void main(String[] args) {
CommonClass cs = new CommonClass();
PriorityBlockingQueue<Character> queue = new PriorityBlockingQueue<Character>();
Producer p1 = new Producer(queue);
Thread t1 = new Thread(p1);
t1.start();
Consumer c1 = new Consumer(queue);
Thread ct1 = new Thread(c1);
ct1.start();
}
}
当我运行它时,我得到的输出为
Producer0produced :a
Consumer0consumed:a
Producer0produced :b
Consumer0consumed:b
Producer0produced :c
Consumer0consumed:c
Producer0produced :d
Consumer0consumed:d
Producer0produced :e
Producer0produced :f
Consumer0consumed:e
Consumer0consumed:f
这是 e 和 f 字母的情况。
这个输出有问题吗??正如我看到的语句 Producer0produced 同时两次,然后是 Consumer0consumed 语句同时针对字母 e 和 f 。
我担心使用此代码我会错过 Producer 生成的任何信息吗?
请指教 ??
感谢您的建议。