都是用thread来处理任务,有什么不一样呢?
Starting a new thread can be a very expensive operation. The thread pool reusesthreads and thus amortizes the cost. Unless you need a dedicated thread, thethread pool is the recommended way to go. By using a dedicated thread you havemore control over thread specific attributes such as priority, culture and soforth. Also, you should not do long running tasks on the thread pool as it willforce the pool to spawn additional threads.
ThreadPool的方式来使用thread,方便高效!事先就已经什么都准备好了,在那里待命;queue一个workitem就可以了。但是一般只用来处理小任务(时间不长的),否则pool中的thread不够用,就需要生成新的或者(已达上限)阻塞其他新来的任务;划不来!
自己new的呢?好控制! 自己动手,丰衣足食嘛!即使用来处理长时间的任务,也没有关系;不像前者,会影响到pool以及其他任务。
Threads in ThreadPool are background threads; All threads created andstarted by a new Thread object are foreground threads.
A background thread does not keep the managed execution environment running.
第二呢,pool中的thread都是background的,自己new的是默认foreground的。这个就有差别了!background的thread,你的process一退出,他跟着就退了。如果用background的thread来悄悄做一个小任务,做完就做完了;但是用foreground的话,这个任务做完,process也跟着退。所以,从这个角度,可以这样说,background是小兵,foreground是将军,小兵不能指挥/控制将军,最多报告一下。
本文深入探讨了使用线程和线程池处理任务的不同之处,包括成本效益、控制特性、线程类型(后台 vs 前台)、以及如何在不同场景下选择合适的工具。通过对比分析,帮助开发者更好地理解并应用这些概念。
716

被折叠的 条评论
为什么被折叠?



