Executor框架维护自己的Workers池,Workers池只记录线程。那么,为什么我们必须传递Thread/Runnable作为参数。为什么没有简单的Task接口?
ExecutorService executorService = Executors.newFixedThreadPool(3); // 3 worker thread
executorService.execute(new Thread()); // why thread? Nobody is going to use this as thread?
我之所以这么问,是因为ThreadPoolExecutor在内部使用传递线程的run方法。
请参阅以下ThreadPoolExecutor:的代码摘录
final void runWorker(Worker w) {
Runnable task = w.firstTask;
w.firstTask = null;
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
clearInterruptsForTaskRun();
try {
beforeExecute(w.thread, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
如果我遗漏了什么重要的东西,请告诉我。
Executor#execute(Runnable)
接受任何Runnable
接口,Thread
也实现Runnable
,因此它是execute()
方法的有效参数。
Oracle文档对The Executor Interface
有何说明?
Executor接口提供了一个名为execute
的方法,该方法被设计为常用的线程创建习惯用法的替代方法。如果r是Runnable
对象,e是Executor
对象,则可以替换
(new Thread(r)).start();
带有
e.execute(r);
在您的内部案例中,它变为:
(new Thread(new Thread())).start();
阅读更多。。。
Runnable
不是线程。它只是一个定义运行方法的接口。调用实现类的run方法不会在新线程中运行它,它只是在您已经所在的线程中调用它,就像调用任何方法一样。从本质上讲,Runnable
正是您建议的Task
接口。