23

我刚刚开始研究 Java 的Executors类和newCachedThreadPool( )方法。根据 API,生成的线程池将现有Thread对象重用于新任务。

我有点困惑这是如何实现的,因为我在 API 中找不到任何方法Thread可以让您设置现有Thread对象的行为。

例如,您可以从一个对象创建一个 对象,这使得调用's方法。但是,API 中没有将 a作为参数的 setter 方法。ThreadRunnableThreadRunnablerun( )ThreadRunnable

我会很感激任何指示。

4

6 回答 6

28

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
        }
    }
}
于 2012-12-04T09:21:51.283 回答
5

线程池具有寻找可运行作业的线程。而不是从线程开始一个新线程Runnable只会调用函数run()。因此,a 中的线程ThreadPool不是使用Runnable您提供的创建的,而是仅检查是否有任何任务准备好执行并直接调用它们的线程。

所以它看起来像这样:

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

于 2012-12-04T09:19:47.470 回答
4

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)

于 2012-12-04T09:20:53.837 回答
2

Executors 在后台为你做所有事情。是的,它只使用现有的线程 API。

下面的链接有使用 Thread 类和 Collection API 实现的线程池的示例实现:http: //www.ibm.com/developerworks/library/j-jtp0730/index.html

于 2012-12-04T09:18:25.147 回答
2

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

于 2012-12-04T09:20:08.313 回答
2

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.

于 2012-12-04T09:23:21.843 回答