从消费者线程引用生产者线程

时间:2015-04-04 14:37:44

标签: java multithreading producer-consumer

我目前正在开发一个使用多个生产者线程和一个消费者线程的程序。我想知道是否有一种简单的方法来准确引用消费者线程消耗的生产者线程。

这是我目前输出的一个例子:

  

消耗的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

任何帮助都会很棒,谢谢!

2 个答案:

答案 0 :(得分:0)

每个生产者都必须将其名称/标识符附加到具有实际信息的队列中(在您的情况下,为int)。

class Data {
    int data;
    String source;
}

而且,不是从队列中写入和读取整数,而是使用Data个实例。

答案 1 :(得分:0)

您可以使用Thread类中的setName(String name)来相应地标识生产者线程。