Search code examples
javamultithreadingconcurrency

Starting Thread from inside it's constructor


Is it acceptable to start a Thread from inside of its constructor after we have initialized fields and is it a bad practice in general to start a Thread from inside of its constructor? For example:

    class A extends Thread{
       private String s;
       private int x
       public A(String str,int xx){
         s = str;
         x = xx;
         start();
       }
      public void run() { System.out.println(s + " " + x);}

    }

Solution

  • As noted in my comment, it's bad practice to extend Thread, and so the question is a non-issue. But again your suggested code is much more than "bad practice" -- it's dangerous. You're performing critical actions on an object before it has been fully constructed, and this can lead to unforeseen and difficult to debug bugs and side effects. Also this greatly limits the flexibility of your code, since now you are forced to use the thread in one and only one way.

    Regarding the separate issue of implementing Runnable or extending Thread, this has been well discussed on this site in multiple threads including this one, and I invite you to take a look.