2015-04-04 108 views
0

我目前正在開發一個使用多個生產者線程和一個消費者線程的程序。我想知道是否有一個簡單的方法可以準確地引用消費者線程消耗的生產者線程。從消費者線程引用生產者線程

這裏是我的輸出的例子至今:

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 

任何幫助將是巨大的,謝謝!

+0

Btw .:你沒有正確地進行同步!全/空和等待測試應該在一個同步塊中。否則,你不能確定狀態(全/空)在此期間沒有改變。 – isnot2bad 2015-04-04 17:15:33

回答

0

每個生產者將不得不將其名稱/標識符附加到實際信息的隊列(在你的情況下,一個int)。

class Data { 
    int data; 
    String source; 
} 

而且,不是從隊列中讀寫整數,而是使用Data實例。