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

Referencing a Producer Thread from a Consumer Thread

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

这是我目前的输出示例:

ConsumerThread consumed: 12 bytes

我希望它是,例如:

ConsumerThread consumed: 12 bytes from ThreadA

ConsumerThread consumed: 62 bytes from ThreadB

这是我的消费者代码,在这种情况下称为 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

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

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

class Data {
    int data;
    String source;
}

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

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