output of this program comes as “Inside Thread Inside Thread” , How this is happening?
class MyThread extends Thread
{
MyThread() {}
MyThread(Runnable r) {super(r); }
public void run()
{
System.out.print("Inside Thread ");
}
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.print(" Inside Runnable");
}
}
class ThreadRunnableBoth
{
public static void main(String[] args)
{
new MyThread().start();
new MyThread(new MyRunnable()).start();
}
}
I can understand how first “Inside Thread” is printing but for second time print I am expecting to print “Inside Runnable” but it prints “Inside Thread” , how this is happening ?
Please explain …..thanks a lot
The
run()method ofjava.lang.Threadsimply callstarget.run(), wheretargetis theRunnableprovided during construction. However, inMyThread, you’ve overridden this functionality; your version ofrun()ignores the target and prints “Inside Thread” instead.One way to fix it is to run your
Runnablewith an instance of the baseThreadclass:Other possibilities would be not to override
run(), or to callsuper.run()from your override.