Reputation: 3452
The output is : RunnableA ThreadB
I don't understand how it comes?? (what happens in the run method in class B)
class A implements Runnable{
public void run(){
System.out.println("RunnableA");
}
}
class B extends Thread{
B(Runnable r){
super(r);
}
public void run(){
super.run();
System.out.println("ThreadB");
}
}
class Demo{
public static void main (String []args){
A a=new A();
Thread t=new B(a);
t.run();
}
}
Upvotes: 0
Views: 2902
Reputation: 125
when you created the object of class B and passed a to it ,the constructor of class b was called .Whats in B's constructor ? super(r); this sets r to be the super call. now in main when you say t.run() it call the overridden method of class B which calls the the run method of the object you have binded super with by saying super(r) .so the run method of a is called first and then "ThreadB" is printed.
Upvotes: 0
Reputation: 48
See carefully the implementation of the run method of Thread class its as under :
public void run() {
if (target != null) {
target.run();
}
}
So calling the run method of Thread calls the run of the Runnable that is passed , In your case you have passed the instance of A while creating Thread t . So call to super.run() calls the run method of Thread class which in turns calls the run method of the A(which is runnable or the target).
Upvotes: 1
Reputation: 37729
Because You have subclass B
and overridden its method run()
.
It'll call B
's method first.
and in B
's run()
it find the super call so it calls super
's run()
(which will execute the provided Runnable
's run()
) first and then execute B
's run()
Upvotes: 2
Reputation: 18682
Thread.run
simply calls the run
method of the Runnable
implementation you gave it. But you should NEVER call Thread.run
, instead call Thread.start
.
Upvotes: 2
Reputation: 8089
As you call super.run()
in B#run
it will execute Thread#run
and next run
method of of the instance of Runnable
you passed to the constructor will be executed.
Upvotes: 3