我目前正在开发一个使用多个生产者线程和一个消费者线程的程序。我想知道是否有一个简单的方法可以准确地引用消费者线程消耗的生产者线程。从消费者线程引用生产者线程
这里是我的输出的例子至今:
ConsumerThread消耗:12个字节
我想它是,例如:
ConsumerThread消耗:12来自ThreadA的字节
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
任何帮助将是巨大的,谢谢!
Btw .:你没有正确地进行同步!全/空和等待测试应该在一个同步块中。否则,你不能确定状态(全/空)在此期间没有改变。 – isnot2bad 2015-04-04 17:15:33