开发者

Is it a good idea to start a thread from its own constructor? [duplicate]

This question already has answers here: Java: starting a new thread in a constructor (3 answers) 开发者_如何学运维 Closed 6 years ago.

Can we call thread_object.start() from within a constructor of this same object?

Is this approach a good idea ?


You can do that, but it is considered as bad practice. There is one paragraph about starting Threads in constructors in this article.

AS nicerobot stated in the comments, your question seem to be a duplicate of this. Have a look at Heath Borders answer there.


Just out of interest - why do you extend Thread? Why not implement Runnable instead, you get more flexibility (e.g. can be executed within a thread you create or an ExecutorService, which is the preferred method).


It's a bad practice, since you cannot be sure that the object is fully initialized. Even if you call the start() method at the end of the constructor it may result in a mess.

Be aware that the processor can do things out of order:

1: MyObject(){
2:  aVariable = anyValue;
3:  this.start();
4: }

The processor is free to execute line 3 before line 2 since they aren't related (in a single threaded fashion), so you could end up with uninitalized variables (even final ones), and other unexpected stuff.


I would suggest to start the thread outside, instead of calling from Constructor. In constructor you should be doing only initialization stuff.


As long the thread you're starting doesn't have a reference to this then you're okay. If the thread does have a reference to this (either passed to the thread of indirectly via an inner class) then it's a bad idea to start it from the constructor as the object isn't fully initialized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜