Im new to java and I have started learning this chapter on threads which left me with number of doubts.
In program 2--->
At 43rd line , thread1 ( object of class MyRunnable) is passed as argument to the Thread constructor . So 43rd line creates a thread object.
In program 1--->
Similarly at 8th line, "this" is the object of Mythread class right ?
Why in program 1 , Thread object and Mythread objects are created inside Mythread class while in program 2, Thread and MyRunnable objects are created inside the ThreadTest class (which contains main method). Why not create both the objects in any one class?
If you are referring to line 8 then yes you are correct to pass 'this' as the parameter.
The Thread constructor you are calling takes a reference to a Runnable object as an argument and when the start() method is called on the Thread object the Runnable object's run() method is executed. In this case the object that creates the Thread object is also the Runnable object and hence you pass 'this' to the Thread's constructor.
Having said that, example one is really bad design because you should never pass 'this' to another object from a constructor. The reason is because until the constructor (and any calling constructors) having completed the object isn't fully initialised and so might not be in a consistent state.
Joined: May 07, 2014
Thank you Tony Docherty for your nice explanation 😊