Need help with Java Producer Consumer Problem, NullPointerException

Posted by absk on Stack Overflow See other posts from Stack Overflow or by absk
Published on 2010-04-16T14:43:06Z Indexed on 2010/04/16 15:03 UTC
Read the original article Hit count: 362

This is my code:

package test;

import java.util.logging.Level;
import java.util.logging.Logger;

class Data{
    int ar[]=new int[50];
    int ptr;

    Data()
    {
        for(int i=0;i<50;i++)
            ar[i]=0;
        ptr=0;
    }

    public int produce()
    {
        if(this.ptr<50)
        {
            this.ar[this.ptr]=1;
            this.ptr++;
            return this.ptr;
        }
        else return -1;
    }

    public int consume()
    {
        if(this.ptr>0)
        {
            this.ar[this.ptr]=0;
            this.ptr--;
            return this.ptr;
        }
        else
            return -1;

    }
}
class Prod implements Runnable{

    private Main m;

    Prod(Main mm)
    {
        m=mm;
    }

    public void run()
    {

            int r = m.d.produce();
            if (r != -1) {
                System.out.println("Produced, total elements: " + r);
            } else
        {
                try {
                wait();
            }
                catch (InterruptedException ex) {
            Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex);
        }
        }

    }
}

class Cons implements Runnable{

    private Main m;

    Cons(Main mm)
    {
        m=mm;
    }
    public void run()
    {
        int r=m.d.consume();
        if(r!=-1)
            System.out.println("Consumed, total elements: " + r);
         else
        {
                try {
                wait();
            }
                catch (InterruptedException ex) {
            Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex);
        }

        }
        notify();
    }

}
public class Main{
    Data d;
    public static void main(String s[]) throws InterruptedException{
        Main m = new Main();
        Prod p = new Prod(m);
        Cons c = new Cons(m);
        new Thread(p).start();
        new Thread(c).start();

    }
}

It is giving following errors:

Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException at test.Cons.run(Main.java:84) at java.lang.Thread.run(Thread.java:619) java.lang.NullPointerException at test.Prod.run(Main.java:58) at java.lang.Thread.run(Thread.java:619)

I am new to Java. Any help will be appreciated.

© Stack Overflow or respective owner

Related posts about java

Related posts about threads