Thread and Runnable
I have come across this statement that to create a new thread it is best to use the Runnable
interface instead of extending the Thread
class. If tha开发者_运维问答t is true, why does Java even allow us to extend the Thread
class. Why not make it final
?
Because the thing you are making is almost certainly not a thread. It's a ThingTheDoesSomeUsefulWork
and you happen to want it to do that useful work on a separate thread. Let's say I'm writing a thing which polls a web server every 30 seconds. Is ThingThatPollsWebServer
a thread? Or is it just a thing that polls a web server.
Besides, making a Runnable
makes it easier to test, plus it gives you the flexibility to run your thing without using a thread, or using the executor framework.
You may want to change the behaviour of a thread or add additional functionality. If this is the case, then extending the Thread class is most suitable.
Using Threads was the old way (before java 5.0) of using, well Threads :). Take a look at the class ExecutorService.
精彩评论