Reputation: 20896
I create a anonymous class and pass it to a thread and when I start the thread, it runs its own class..
Can someone explain, what happens to the object-r that is passed to the Thread?
public class Interface1{
public static void main(String[] args){
Runnable r = new Runnable(){
public void run(){
System.out.println("Cat");
}
};
Thread t = new Thread(r){
public void run(){
System.out.println("Dog");
}
};
t.start();
}
}
Upvotes: 0
Views: 150
Reputation: 659
Whenever you start a thread, java.lang.Thread's run() function is called. If you look at the source code of Thread.java, it first checks for the target, which is the Runnable passed in the constructor of the Thread class. This runnable is nothing but your class that has implemented the Runnable interface and thus overridden its run() function.
Since its the run function of the runnable now that is used, you should implement the logic inside your runnable. Keep in mind, that a new OS thread will be only launched by Thread class if target/runnable is not null, otherwise Thread.run() will execute in the same thread as the caller.
Upvotes: 0
Reputation: 31699
The javadoc for Thread
's run
method says:
If this thread was constructed using a separate
Runnable
run object, then thatRunnable
object'srun
method is called; otherwise, this method does nothing and returns.
The javadoc for start
says it just calls run
. I don't see anything else that runs the Runnable
object. So I think we can assume that the only way to run your r
object is through the run
method of the Thread
class. However, you've overridden it.
If you want your overriding run
method to also run the r
object, consider adding this somewhere in your run
:
super.run();
Upvotes: 0
Reputation: 280132
When you pass a Runnable
as a constructor argument to Thread
, it sets an instance field called target
, which it usually uses when it start()
s.
But you've overriden Thread#run()
which is normally
@Override
public void run() {
if (target != null) {
target.run();
}
}
with
public void run(){
System.out.println("Dog");
}
In the anonymous class you've created.
So your code runs instead instead of executing target.run()
where target
is your Runnable
instance.
Upvotes: 6
Reputation: 41220
If you see the code in Thread.java -
634 public void [More ...] run() {
635 if (target != null) {
// target is runnable instance which initialized in constructor
636 target.run();
637 }
638 }
If you pass runnable object through constructor then it executes But here you override the run method of Thread class itself in your Anonymous inner class so it executed overrided method.
Upvotes: 0