How Does a Cached Thread Pool Reuse Existing Threads

ぃ、小莉子 提交于 2019-11-30 08:21:12

Executors does everything for you in the background. And yes it uses the existing thread API only.

Below link has sample implementation of Thread pool implemented using Thread class and Collection API: http://www.ibm.com/developerworks/library/j-jtp0730/index.html

Basically imagine each thread from the pool doing this:

public void run() {
    while(true) {
        if(tasks available) {
           Runnable task = taskqueue.dequeue();
           task.run();
        } else {
           // wait or whatever
        }
    }
}

Threads are created only once in the Thread Pool API (except in the cases when due to some exception the thread exits abruptly)

The Worker threads poll the Queue to see if there is a task and use it. So the threads never exit.

It is just an abstraction that Threads are reused (Abstraction for they never actually stop). Obviously they stop after idle timeout and shutdown request.

Runnable -----> Thread Pools (Some worker thread consumes that Runnable and others wait for some more Runnables)

The threadpool has threads that look for runnable jobs. Instead of starting a new thread from the Runnable the thread will just call the function run(). So a thread in a ThreadPool isn't created with the Runnable you provide,but with one that just checks if any tasks are ready to be executed and calls them directly.

So it would look something like this:

while(needsToKeepRunning()){
    if(hasMoreTasks()){
        getFirstTask().run();.
    }
    else
    {
        waitForOtherTasks();
    }
}

Of course this is overly simplified the real implementation with the waiting is much more elegant. A great source of information on how this really works can be found in Concurrency in Practice

Well the thread only have to call Runnable.run() on the runnables which are assigned to him...

A simplified explanation is that when you pass a Runnable to the ExecutorService the Runnable is put into a queue. The ThreadPool worker threads reads from this queue and invokes the queued Runnables run() method.

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