【发布时间】:2014-11-01 23:28:46
【问题描述】:
Executor 框架维护自己的工人池,这些工人池只是线程。然后,为什么我们必须传递 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);
}
}
如果我在这里遗漏了什么重要的东西,请告诉我。
【问题讨论】:
标签: java multithreading threadpool runnable executorservice