Reputation: 136
we knew that we can create a new thread by creating a new class thats extends thread and then to create an instance of that thread..while going through this topic i saw an example in my book which is as follows.
class NewThread extends Thread{
NewThread(){
super("demo thread");
System.out.println("child thread:"+this);
start();
}
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println("child thread"+i);
Thread.sleep(500);
}
} catch(InterruptedException e){
System.out.println("child interrupted");
}
System.out.println("exiting child thread");
}
}
in this example i am able to understand all those things except the constructor part in which we are not using any instance(thread) to call start().so my question is how the start() method is called without any thread.
Upvotes: 1
Views: 96
Reputation: 38910
Below code is responsible for calling start()
method on your NewThread
instance in NewThread
constructor, which calls start()
method in Thread
class, which calls run()
method.
NewThread(){
super("demo thread");
System.out.println("child thread:"+this);
start();
}
Flow:
NewThread() -> start() -> Thread start() -> native start0() -> run()
Refer to this SE question for internals of Thread
class start()
method :
What's the difference between Thread start() and Runnable run()
Upvotes: 0
Reputation: 383
You are inheriting the start() method from the class Thread that your NewThread class extends. So you can call it like any other method.
Same goes for the run() method which could use the @Override annotation in order to make the concept of inheritance clearer.
@Override
public void run() {
try{
for(int i = 5; i > 0; i--) {
System.out.println("child thread" + i);
Thread.sleep(500);
}
} catch(InterruptedException e) {
System.out.println("child interrupted");
}
System.out.println("exiting child thread");
}
Upvotes: 1
Reputation: 162
This start() method is called on the thread instance, which has just been created in this constructor.
Upvotes: 0
Reputation: 229
It is valid because method start()
is inherited from Thread
class, so you can call it like any other class method.
Upvotes: 0