线程和可运行 [英] Thread and Runnable
问题描述
我遇到过这样的说法:创建一个新线程,最好使用Runnable
接口而不是扩展Thread
类.如果是这样,为什么Java甚至允许我们扩展Thread
类.为什么不将其设为final
?
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 that is true, why does Java even allow us to extend the Thread
class. Why not make it final
?
推荐答案
因为您所做的事情几乎肯定不是线程.这是一个ThingTheDoesSomeUsefulWork
,您碰巧希望它在单独的线程上完成这项有用的工作.假设我写的东西每30秒轮询一次Web服务器. ThingThatPollsWebServer
是线程吗?还是轮询网络服务器的事情.
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.
此外,制作Runnable
使其更易于测试,此外,它还使您可以灵活地运行自己的东西而无需使用线程或使用执行程序框架.
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.
这篇关于线程和可运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!