0

I'm pretty new to threads and just trying to get a grip on the basics.So, I tried the following code to print odd and even numbers one after the other.

But I'm getting a null pointer.

public class P {

public static void main(String[] args) throws InterruptedException {

     Print print = new Print(false);
     Even e =new Even();
     Odd o = new Odd();  
     e.start();
     o.start();
}

}

class Even extends Thread { Print print;

public void run()
{
  try {
    print.printeven();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

}

class Odd extends Thread { Print print;

public void run()
{
  try {
    print.printodd();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

}

class Print {

public  boolean flag=false;

Print(boolean flag){

    this.flag=flag;
}

synchronized void printodd() throws InterruptedException
   {

    for(int i=1;i<10;i=i+2)
        if(!flag)
        {
        System.out.println(i);
        notifyAll();
        flag=true;
        }
        else
        {
            wait();
        }
   }

synchronized void printeven() throws InterruptedException
   {

    for(int i=2;i<=10;i=i+2)
        if(flag)
        {
        System.out.println(i);
        notifyAll();
        flag=false;
        }
        else
        {
            wait();
        }
   }

}

If someone could explain in detail what I'm doing wrong here and give a basic idea how to go about debugging this.

Ankush Dutt
  • 143
  • 8

2 Answers2

0

You have not instantiated Print instance in both ODD and EVEN classes.

Do this for both Even and Odd constructors.

public Odd(Print print) 
{ 
  this.print = print;
}

When instantiating do like this.

 Print print = new Print(false);
 Even e =new Even(print);
 Odd o = new Odd(print);  
Vishma Dias
  • 630
  • 6
  • 11
0

See You are doing Nothing with

Print print = new Print(false); // this statement

in main() method.

pass the "print" object to Odd and Even class Constructor.

You are getting Null pointer Because you are not initialising print Object Odd and Even class.

Duega
  • 73
  • 1
  • 10