线程和可运行 [英] Thread and Runnable

查看:73
本文介绍了线程和可运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过这样的说法:创建一个新线程,最好使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆