0

The program is running without any error when i'm trying to start Thread from main() but Why i'm getting NullponterException when i'm trying to start Thread from constructor.

class MyThread extends Thread
{

    static MyThread obj;
    MyThread()
    {
        obj.start();
         for(int i=1;i<20;i++)
        System.out.println("getName:"+obj.currentThread().getName());
    }

   public void run()
   {
       for(int i=1;i<20;i++)
     System.out.println("getName:"+obj.currentThread().getName());
   }


   public static void main(String... s)
   {
      obj=new MyThread();

   }
}
SegFault
  • 2,526
  • 4
  • 21
  • 41
Shadab Faiz
  • 2,380
  • 1
  • 18
  • 28

1 Answers1

3

The problem is that your code does things in the wrong order. When you say

obj = new MyThread();

the code does this:

  1. Create a new MyThread object. Creating the new object includes executing the constructor. The value of new MyThread() will be a reference to the new object.
  2. Assign this reference to obj.

This doesn't work, because step 1 tries to use obj before it gets a value in step 2.

The solution (I think) is to realize that, when you're in the constructor, this is a reference to the object being created. Since that seems to be what you want obj to be, you can get your program to run by replacing

obj.start();

with

this.start();

or, equivalently, just

start();

I tried this and it seems to work. However, I do not recommend doing this in a real program. Starting a thread object before its constructor has completed strikes me as dangerous. (What would happen if, after the start() call, the rest of the constructor throws an exception? I'd have to look it up to figure out the exact semantics, but this would mean that you're running a thread whose construction has never finished running. What if the run() method of the thread tries to access instance variables that aren't set until later in the constructor?) If you think you want something like this, then most likely you need to rethink your design. However, a simple way to get around this is to provide a static factory method (which has other advantages) that calls a private constructor, then calls start() on the new object [whose construction has successfully completed], then does anything else that you want to do after the start().

[P.S. I'm saying "I think" this is the right solution, because it's not completely clear what you're trying to accomplish.]

ajb
  • 31,309
  • 3
  • 58
  • 84