Reputation: 27455
I've write the following example:
public class MyThread extends Thread{
MyThread(Runnable r){
super(r);
}
public void run(){
System.out.println("run");
}
}
public static void main(String[] args)
{
Thread t = new MyThread(new Runnable() {
@Override
public void run() {
System.out.println("rrrrrrrrrruuuuuuuuuuuun");
}
});
t.start(); //run
}
Why does run methdo defined in MyThread
was called instead?
Upvotes: 0
Views: 73
Reputation: 477854
Because you the MyThread.run
is not override, but the Runnable.run
is. Now if you look at your implementation of MyThread.run
, the stored Runnable
plays no part in it. In other words, it doesn't matter what kind of runnable you give with the constructor. You should use:
public static void main(String[] args)
{
Thread t = new MyThread() {
@Override
public void run() {
System.out.println("rrrrrrrrrruuuuuuuuuuuun");
}
});
t.start(); //run
}
As @BorisTheSpider notes, overriding a Thread
is in general not good practice: a Thread
has the responsibility to start a Thread
and give control to a runnable. A better implementation would be:
public static void main(String[] args)
{
Thread t = new Thread(new MyThread() {
@Override
public void run() {
System.out.println("rrrrrrrrrruuuuuuuuuuuun");
}
}));
t.start(); //run
}
Upvotes: 3
Reputation: 692231
Because the default behavior of a thread constructed with a Runnable is to delegate to the runnable passed as argument to the constructor. But you overrode run()
in the thread itself, so instead of delegating to the runnable, it executes the code inside the overridden run()
method.
For the record, here's the default implementation of Thread.run(), that you overrode:
private Runnable target;
public void run() {
if (target != null) {
target.run();
}
}
Upvotes: 3