【发布时间】:2026-01-17 17:10:01
【问题描述】:
我对什么时候创建新线程感到困惑,就像执行者一样。我的理解是:对于cachedthreadpool,是根据任务的提交来创建新的线程。至于fixedthreadpool和singlethread,不管任务的提交,线程都是提前创建的。是不是我的理解错了?
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new LiftOff());
ExecutorService exec = Executors.newFixedThreadPool(3); // Are the three threads created
// after this line executes?
exec.execute(new LiftOff());
ExecutorService exec = Executors.newSingleThreadExecutor(); // Is the single thread created
// after this line executes?
exec.execute(new LiftOff());
【问题讨论】:
-
您可以使用调试器或查看
Executors的代码来回答这些问题。 -
这些方法中的每一个都有一个接受
ThreadFactory的变体,你可以传入你自己的实现来记录何时请求线程。
标签: java multithreading