gpt4 book ai didi

java - 为什么执行器框架中的任务是线程

转载 作者:行者123 更新时间:2023-12-01 22:43:28 28 4
gpt4 key购买 nike

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 接口(interface)和 Thread还实现了 Runnable 因此它是 execute() 方法的有效参数。

什么Oracle documentation关于执行器接口(interface)

Executor 接口(interface)提供了一个方法,execute,旨在替代常见的线程创建惯用语。如果 r 是一个 Runnable 对象,e 是一个 Executor 对象,您可以替换

(new Thread(r)).start();

e.execute(r);
<小时/>

在你的情况下,内部它变成:

(new Thread(new Thread())).start();

Read more...

关于java - 为什么执行器框架中的任务是线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25729435/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com