'Starting Thread from inside it's constructor [duplicate]

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 1:[1]

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.

Solution 2:[2]

In general it's good practice to control an object from the outside only, hence getter and setter methods etc..the same applies here, starting a thread like that just smells bad, don't do it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Richard Guy