It’s quiet right that we should never override the start method of a thread but I was just practicing java when I was confused with two different behaviors…..
I’m trying to override start method of Thread class.Below is the code:
package myPackage;
public class MainThreadUsingThread extends Thread{
@Override
public void run() {
System.out.println("-run in t1");
System.out.println("");
}
@Override
public void start() {
System.out.println("in start in t1");
super.start();
}
/*public static void main(String[] args) {
System.out.println("hii");
Thread t3=new Thread(new MainThreadUsingThread());
t3.start();
}*/
}
class A11 {
public static void main(String[] args) {
System.out.println("hii");
Thread t1=new Thread(new MainThreadUsingThread());
t1.start();
Thread t2=new Thread() {
@Override
public void run() {
System.out.println("run in t2");
}
@Override
public void start() {
System.out.println("in start in t2");
super.start();
}
};
t2.start();
}
}
In case of Thread “t2”, I’m getting the overridden start method but not in case of Thread “t1”.
Plz help me come out of this confusion.
Also is there any way to do the same (override, as far as it is not a good practice) in case of runnable interface.
Your
new MainThreadUsingThread()is being used asRunnable(becauseThreadimplementsRunnable). The thread executesRunnable.run(), that’s why you don’t get the overridenstart.When
Thread.startis called, it starts a new thread and callThread.runin that new thread.You should do this:
In
Thread, itsrunmethod starts theRunnablethat is used to construct thatThread, or does nothing if noRunnableis used to construct it. If you extendsThreadand overrideThread.run, this effectively changed what the thread does.If you use
new Thread(new MainThreadUsingThread()), this effectively call the constructorThread(Runnable target)and constructs a newThread. Just like doing this: