对于 newCachedThreadPool 线程池,我看到的说法是:
“如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。“
为何不 reuse 这些超时的线程,而要去新创建一个线程添加到池中?这样不是性能更低么?
1
Monstercat 2017-08-08 11:27:18 +08:00 via Android
开太多线程也会影响性能
|
2
lovedebug 2017-08-08 11:31:36 +08:00
挂起的线程可能永远不退出怎么办? 线程池最后可能没有可用线程了。
|
4
zhaohui318 2017-08-08 12:00:35 +08:00
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors 这是两句话,分开来理解。 有需求时如果有空闲的线程当然会 reuse 正是没要需求,线程才会空闲超时然后被清除来节省内存资源 |
5
ihuotui 2017-08-08 12:00:59 +08:00 via iPhone
那就不是用这个类了,不同类的目的不一样。
|
6
honeycomb 2017-08-08 12:33:15 +08:00 via Android
它是说线程未使用(没有任务)长达 60 秒后抛弃。
楼上的 @zhaohui318 说得很清楚 |