001    package pnc;
002    import java.awt.*;
003    import cs101.awt.ColorField;
004    import cs101.util.semaphore.GCS;
005    import cs101.util.semaphore.GraphicalSemaphore;
006    
007    public
008    class MultiBuffer extends Buffer {
009      private int size;
010      private ColorField[] locations;
011      private int produceIndex = 0;
012      private int consumeIndex = 0;
013      private Object produceLock = new Object();
014      private Object consumeLock = new Object();
015    
016      public MultiBuffer(int size) {
017        // setup super class instance variables
018        super();
019        this.read = new GCS(size, size, "Read");
020        this.write = new GCS(size, 0, "Write");
021        
022        // setup my instance variables
023        this.size = size;
024        this.locations = new ColorField[size]; 
025    
026        // add display panel for buffer
027        this.bufferPanel.add(this.setupBuffer());                
028      }
029    
030      public void produce() {
031        this.write.request();    
032        synchronized (produceLock) {
033          this.locations[this.produceIndex].changeState(true);
034          // incriment index and wrap if needed
035          if (this.size == ++this.produceIndex)
036            this.produceIndex = 0;
037        }
038        this.read.release();
039      }
040    
041      public void consume() {
042        this.read.request();
043        synchronized (consumeLock) {
044          this.locations[this.consumeIndex].changeState(false);
045          // incriment index and wrap if needed
046          if (this.size == ++this.consumeIndex)
047            this.consumeIndex = 0;
048        }
049        this.write.release();
050      }
051    
052      private Panel setupBuffer() {
053        
054        Panel statusPanel = new Panel();
055    
056        GridBagLayout layout = new GridBagLayout();
057        statusPanel.setLayout(layout);    
058        GridBagConstraints con = new GridBagConstraints();    
059        con.gridwidth = 1; con.gridheight=1;
060        con.fill = GridBagConstraints.HORIZONTAL;
061        con.weightx = 1/this.size; con.weighty = 0;
062        Dimension dim = new Dimension(20,20);
063        
064        for (int i = 0; i < this.size; i++) {
065          this.locations[i] = new ColorField(false, dim, Color.blue,
066                                         Color.lightGray);
067          con.gridx = i; con.gridy = 0;
068          layout.setConstraints(this.locations[i], con);
069          statusPanel.add(this.locations[i]);          
070      
071        }   
072        
073        return statusPanel;
074    
075      }
076    
077    }
078