newCachedThreadPool如何重用线程? [英] How newCachedThreadPool reuses threads?
问题描述
javadoc说Executors.newCachedThreadPool
返回的服务会重用线程.这怎么可能?
线程只能通过调用start
启动一次.那么他们如何实现呢?此服务的线程正在无限循环中运行,并且它们的Runnable
-s是否按需替换?
The javadoc says that the service returned by Executors.newCachedThreadPool
reuses threads. How is this possible?
A thread can only be started once by calling start
. So how do they implement it? Threads of this service are running in an infinite loop and their Runnable
-s are replaced on demand?
推荐答案
一个Runnable可以调用另一个Runnable.
An Runnable can call another Runnable.
每个线程仅运行一个主Runnable,但该Runnable从共享的BlockingQueue中获取Runnable并对其进行调用,直到关闭为止.
Each thread runs only one main Runnable, but that Runnable takes Runnables from a shared BlockingQueue and calls these until it is shutdown.
简化了.
final BlockingQueue<Runnable> queue = ...
Runnable runs = new Runnable() { public void run() {
while(running)
queue.take().run();
}};
您可以阅读代码以查看其实际效果.
You can read the code to see how it really does it.
这篇关于newCachedThreadPool如何重用线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!