How newCachedThreadPool reuses threads?

 ̄綄美尐妖づ 提交于 2019-12-10 13:53:54

问题


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?


回答1:


An Runnable can call another Runnable.

Each thread runs only one main Runnable, but that Runnable takes Runnables from a shared BlockingQueue and calls these until it is shutdown.

Simplified it does.

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.



来源:https://stackoverflow.com/questions/12071999/how-newcachedthreadpool-reuses-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!