在Executor执行框架源代码分析(一)中已经介绍过ThreadFactory和Executor的作用和关系。本文继续讨论ThreadFactory和Executor的具体实现。
一、ThreadFactory
ThreadFactory的目的是为了让用户可以创建定制化的线程。所以,除了一个DefaultThreadFactory之外,这个接口在JDK中基本没有具体的实现,主要还是用户自己进行定制。这里我们看一下 DefaultThreadFactory的实现,了解一下ThreadFactory的具体使用方式即可。DefaultThreadFactory的源代码如下:
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "pool-" &#