I am trying to implement the producer consumer problem by creating my own semaphores. When compiling and running the program I am getting the error :
Exception in thread "Producer" java.lang.NullPointerException
at Producer.run(Producer.java:23)
Exception in thread "Consumer" java.lang.NullPointerException
at Consumer.run(Consumer.java:24)
I know that this has something to do with the methods valueConsumed.P() and valueProduced.P(). Did I not implement these methods right in the Producer, Consumer, and Semaphore Classes?
Producer
public class Producer extends Thread{
private Buffer sharedLocation;
private Semaphore valueProduced;
private Semaphore valueConsumed;
public Producer (Buffer shared) {
super("Producer");
sharedLocation = shared;
}
public void run() {
for (int count = 1; count <= 4; count++){
try {
Thread.sleep((int) (Math.random() * 3001));
valueConsumed.P();
//check to see if the value has been consumed P( valueConsumed );
sharedLocation.set(count);
//let consumer thread know it can consume the value
valueProduced.V();
}
catch (InterruptedException exception) {
exception.printStackTrace();
}
}
System.err.println(getName() + " done producing.");
}
}
Consumer
public class Consumer extends Thread{
private Buffer sharedLocation;
private Semaphore valueProduced;
private Semaphore valueConsumed;
public Consumer (Buffer shared) {
super("Consumer");
sharedLocation = shared;
}
public void run() {
int sum = 0;
for (int count=1; count<=4; count++) {
try{
Thread.sleep((int) (Math.random() * 3001));
valueProduced.P();
sum += sharedLocation.get();
valueConsumed.V();
}
catch (InterruptedException exception) {
exception.printStackTrace();
}
}
System.err.println(getName() + " done consuming. and sum= " + sum);
}
}
Semaphore
public class Semaphore{
private int value;
public Semaphore(int initval)
{
value=initval;
}
public void P(){
if( value>0)
value=value-1;
else
try {
Thread.sleep((int) (Math.random() * 3001));
}
catch (InterruptedException exception){
exception.printStackTrace();
}
}
public void V(){
value=value+1;
}
}