Given this sample code:
Runnable r = new Runnable() {
public void run() {
System.out.print("Cat");
}
};
Thread t = new Thread(r) {
public void run() {
System.out.print("Dog");
}
};
t.start();
why is the output Dog and not Cat??
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The implementation of
runinThreadsimply calls theRunnableprovided in the constructor, if there is one. You’re overriding that code, so if the new thread simply has itsrunmethod called regardless, theRunnableis ignored. Of course, you should be able to look at the source code to check that… (I’ve just done so, and while I’m not going to post the source here, it does exactly what I’ve described.)What you’ve really exposed is an encapsulation problem –
Threadshouldn’t have these different, potentially conflicting, ways of saying what the thread should do. Basically, you should almost never extendThreaddirectly. Just because it’s been designed badly doesn’t mean you have to abuse that poor design 😉EDIT: This is actually documented, in a somewhat roundabout way.
start()is documented as:And
run()is documented as:So the
run()method is called as perstart(), but you’ve overriddenrun(), which is the only method which will call theRunnableprovided in the constructor.Note that if you’d overridden the method like this:
Then the output would be “CatDog”.