General discussion about thread (Confusion)
I just want to know what is the difference between the following two methods of invoking the thread.
Please look at the two pictures of the two scenarios
My problem is that the behavior i faced is when i follow "scenario 1" i lost control of my program and the
"// other commands" in MyClass didnt run
when i followed scenario two my sequence was smooth. has anyone noticed this behavior or is it a malfunction开发者_运维技巧?
Kindly give your opinions.
Regards,
I guess that instead of implementing Thread
(which is not an interface as already stated) you mean to implement Runnable
.
So the question seems to be (it's just a guess, since your question is missing): who should start the thread - MyClass
or MyThread
?
Basically, I'd prefer scenario 1 since MyThread
is actually just a runnable task and should not additionally handle the thread itself.
Thus MyClass
should create and start the thread. This would additionally allow you to keep references to the spawned threads and maybe call join()
or other methods on them later on.
As a sidenote, I'd change MyThread
into this: public class MyRunnable implements Runnable { ... }
You might want to access the Thread object, e.g. to wait for it to finish or to poll it's state. In scenario 2 you might not do this because variable t
is not accessible from the client code. In order to achieve this, you either had to make t
visible from the outside code or override the Thread
methods (which would be a bit futile). If invokeThread
is meant as some sort of convenience method, you could consider returning t
.
If scenario 2 is meant as "MyThread
encapsulates running a thread and controls it's state", you don't have to extend Thread
(which reads a bit confusing).
As mentioned in the other comment, I would second implementing Runnable
rather than subclassing Thread
for cleaner code.
精彩评论