Starting a thread within a constructor may cause unexpected results. If the class is extended, the thread may start before the subclass constructor has completed its initialization, which may not be intended.

Avoid starting threads in constructors. Typically, the constructor of a class only constructs the thread object, and a separate start method should be provided to start the thread object created by the constructor.

In the following example, because the Test constructor implicitly calls the Super constructor, the thread created in the Super constructor may start before this.name has been initialized. Therefore, the program may output "hello " followed by a null string.

In the following modified example, the thread created in the Super constructor is not started within the constructor; main starts the thread after this.name has been initialized. This results in the program outputting "hello my friend".

  • IBM developerWorks: Don't start threads from within constructors.