I get tons of meaningless (for me) exception when run this code. Not sure where I could make a mistake... Basically I want my producer to puts alpha chars in the buffer and consumers to get them from a buffer and print. I just started to learn multithreading and I have no idea what could be the potential problem in this code. I tried to implement in-class example. I really apologize if it is a dumb question...
public class Driver {
public static void main(String[] args) {
new Consumer("Consumer1");
new Consumer("Consumer2");
new Consumer("Consumer3");
new Producer("Producer1");
}
}
public class Producer implements Runnable{
private Buffer buf = null;
public Producer(String name){
buf = Buffer.getInstance();
new Thread(this, name).start();
}
public void run(){
char character = 'A';
for(; character < 'Z'; character ++){
buf.put(character);
System.out.println("Producer " + Thread.currentThread().getName() + " puts " + character);
}
Consumer.done = true;
}
}
public class Buffer {
private static Buffer instance = null;
private boolean full = false;
private boolean empty = true;
private char[] arr;
private int i;
private Buffer(){
arr = new char[26];
i = 0;
}
public static synchronized Buffer getInstance(){
if(instance != null){
instance = new Buffer();
}
return instance;
}
public synchronized void put(char c){
while(full){
try{
wait();
}catch(Exception e){}
}
arr[i++] = c;
empty = false;
if(i == 25){
full = true;
notifyAll();
}else{
full = false;
}
}
public synchronized char get(){
while(empty){
try{
wait();
}catch(Exception e){}
}
if(--i == 0){
empty = true;
}else{
notifyAll();
}
full = false;
return arr[i];
}
}
public class Consumer implements Runnable{
private Buffer buf = null;
public static boolean done = false;
public Consumer(String name){
buf = Buffer.getInstance();
new Thread(this, name).start();
}
public void run(){
while(!done){
System.out.println("Producer " + Thread.currentThread().getName() + " gets " + buf.get());
}
}
}
Exception in thread "Consumer2" Exception in thread "Consumer3" Exception in thread "Consumer1" Exception in thread "Producer1" java.lang.NullPointerException
at Producer_consumer.Consumer.run(Consumer.java:15)
at java.lang.Thread.run(Thread.java:745)
java.lang.NullPointerException
at Producer_consumer.Consumer.run(Consumer.java:15)
at java.lang.Thread.run(Thread.java:745)
java.lang.NullPointerException
at Producer_consumer.Producer.run(Producer.java:16)
at java.lang.Thread.run(Thread.java:745)
java.lang.NullPointerException
at Producer_consumer.Consumer.run(Consumer.java:15)
at java.lang.Thread.run(Thread.java:745)