package lab8multiplethread;

//
public class SharedBuffer {
    private long val = 0;
    private boolean PresentFlag = false;
    private int writeCounter=0, readCounter=0;
    
    private void addWrite()
    {
        writeCounter++;
    }
    
    public int getNumWrites()
    {
        return writeCounter;
    }
    
    private void addRead()
    {
        readCounter++;
    }
    
    public int getNumRead()
    {
        return readCounter;
    }

    public synchronized long consume(){
	while (!PresentFlag){
	    try{ 
		wait(); 
	    }catch(InterruptedException e){}
	}
	PresentFlag = false;
        addRead();
	this.notifyAll();
	return val;
    }
    
    
    public synchronized void produce(long x){
	while (PresentFlag){
	    try{
		wait();
	    }catch(InterruptedException e){}
	}
	val = x;  
	PresentFlag = true;
        addWrite();
	this.notifyAll();
    }
}
