【发布时间】:2015-04-04 14:37:43
【问题描述】:
我目前正在开发一个使用多个生产者线程和一个消费者线程的程序。我想知道是否有一种简单的方法可以准确地引用消费者线程从哪个生产者线程中消费。
到目前为止,这是我的输出示例:
ConsumerThread 消耗:12 个字节
我希望它是,例如:
ConsumerThread 消耗:来自 ThreadA 的 12 个字节
ConsumerThread 消耗:来自 ThreadB 的 62 个字节
这是我的消费者代码,在本例中称为 CPU:
class CPU implements Runnable {
private final Vector processingQueue;
private final int SIZE;
public CPU (Vector processingQueue, int size) {
this.processingQueue = processingQueue;
this.SIZE = size;
}
public void run() {
while (true) {
try {
System.out.println("CPU processing: " + consume() + " bytes");
Thread.sleep(50);
} catch (InterruptedException ex) {
Logger.getLogger(CPU.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private int consume() throws InterruptedException {
//wait if queue is empty
while (processingQueue.isEmpty()) {
synchronized (processingQueue) {
System.out.println("Queue is empty " + Thread.currentThread().getName()
+ " is waiting , size: " + processingQueue.size());
processingQueue.wait();
}
}
//Otherwise consume element and notify waiting producer
synchronized (processingQueue) {
processingQueue.notifyAll();
return (Integer) processingQueue.remove(0);
}
}
}
这是我的一个生产者的示例,名为 OperatingSystem:
public class OperatingSystem extends Thread {
private final Vector processingQueue;
private final int SIZE;
public OperatingSystem (Vector processingQueue, int size) {
this.processingQueue = processingQueue;
this.SIZE = size;
}
private void produce(int i) throws InterruptedException {
// suspend producing if queue is full
while (processingQueue.size() == SIZE) {
synchronized (processingQueue) {
System.out.println("Queue is full " + Thread.currentThread().getName()
+ " is waiting , size: " + processingQueue.size());
processingQueue.wait();
}
}
// producing element and notify consumers
synchronized (processingQueue) {
processingQueue.add(i);
processingQueue.notifyAll();
}
}
public void run() {
//OperatingSystem using 300bytes
for (int i = 0; i <= 300; i++) {
System.out.println("Operating System producing: " + i + " bytes");
try {
produce(i);
} catch (InterruptedException ex) {
Logger.getLogger(OperatingSystem.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}//OperatingSystem
任何帮助都会很棒,谢谢!
【问题讨论】:
-
顺便说一句:您没有正确进行同步!测试满/空和等待应该在一个同步块中。否则,您无法确定状态(满/空)在此期间没有发生变化。
标签: java multithreading producer-consumer