想知道是如何实现的,自己猜测最终还是需要Thread来实现。
打开ThreadPoolExecutor类,然后搜索Thread(这个
发现如下:
跟踪这里的getThreadFactory()方法:
public ThreadFactory getThreadFactory() {
return threadFactory;
}
看看threadFactory是在哪里进行赋值的。
以下来跟踪源码:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
可以看到这里有一个Executors.defaultThreadFactory()。
进入Executors类:
public static ThreadFactory defaultThreadFactory() {
return new DefaultThreadFactory();
}
继续看看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-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
可以看到这里最终还是调用了Thread来实现线程池。
疑问还是很多的,这里的
private final BlockingQueue<Runnable> workQueue;
是干啥用的?????