Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
I have two questions about multithreaded programming. I read a few answers on the internet, but still I can’t find a satisfying answer.
-
Implementing the Runnable is preferred over extending the thread class. Why?
-
How is it that we are able to get away with overriding just the run() method?
According to ‘The Complete Reference to Java’ by Herbert Schildt, If we are not overriding any methods of Thread class other than run(), it’s better we implement Runnable.
My 2nd question might sound a bit silly, but I seem to be missing something and I’m not sure about how the whole thing works.
Because it allows your class to extend another class if it wants to instead of being forced to extend
Thread.You can certainly override other methods but the
Threadobject will call therun()method when the thread is started. That’s how it works. The defaultThread.run()method is:If you call the
Threadconstructor with aRunnablethen that is what thetargetis set to. If you instead extendThreadand@Overridetherun()method then that is the method that will be called when the thread object is started.That’s how the
Threadclass works.You may have misspoke here and were instead asking why we only need to implement the
run()method inRunnable().Runnableis an interface with a singlerun()method that you must implement.Threadis a concrete class that you are extending. You can override any methods in a concrete class unless the class isfinalor the method isfinal.Make sure you use proper Java terminology and don’t mixup
implementandoverride.