0

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);}

    }
danronmoon
  • 3,814
  • 5
  • 34
  • 56
  • 3
    First of all, it's bad practice to extend Thread. So this is a non-issue. But even if this wasn't the case, then yes, what you've posted is not a good idea -- to critically use an object before it has completed construction is never good. – Hovercraft Full Of Eels Apr 17 '16 at 00:03
  • Could you explain why extending a thread is a bad practice?I can see a restriction( not being able to extend), but other than that, it's pretty much a matter of choice. – Andrija Boricic Apr 17 '16 at 00:14

2 Answers2

0

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.

Richard Guy
  • 470
  • 4
  • 12
0

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.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373