还是直接上源码吧
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,钱三强生平简介
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
上⾯这段代码就是wSingleThreadExecutor⽅法得源码,因为FinalizableDelegatedExecutorService使⽤的是代理模式,所以接下来再看⼀下ThreadPoolExecutor的构造函数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
学习歌曲maximumPoolSize < corePoolSize ||
大班月饼keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.maximumPoolSize = maximumPoolSize;
人员推销
this.workQueue = workQueue;
this.keepAliveTime = Nanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
这⾥有两个参数需要注意以下:corePoolSize和maximumPoolSize。看⼀下这两个参数的说明:
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is t
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
意思⼤概是说corePoolSize是线程池中的最⼤线程数量,⽽maxmumPoolSize意思是阻塞队列最⼤的阻塞线程数量,然后我们再回去看⼀下wSingleThreadService⽅法,给出的这两个参数都是1,那么问题来了,如果我想要搞⼀个只有⼀个运⾏线程的线程池时这个⽅法就不能满⾜我们的需求了,那么直接new⼀个ThreadPoolExecutor如:new ThreadPoolExecutor(1, 0, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())可不可以呢?答案是:不可以,因为在ThreadPoolExecutor的构造函数⾥第⼀个if语句就判断了,如果maximumPoolSize <= 0就会抛出⼀个异常。再回来看看,如果我们使⽤了JDK⾃带的newSingleThreadPool会发⽣什么情况:
素炒冬瓜1. 第⼀次submit⼀个线程,因为没有在运⾏的线程,所以该线程不会被提交到阻塞队列⾥,⽽是直接start运⾏。
2. 紧接着我们再submit⼀个线程,这次因为已经有⼀个线程在运⾏了,并且运⾏的线程数量等于corePoolSize所以,这个线程会被提交到阻塞队列。
3. 再submit第三个线程,这次就是饱和策略⼤显⾝⼿的时候了。
What,我原本是不想让第⼆个线程提交的,这样不就算是重复提交了吗?对,是重复提交。所以看来⾃带的JDK给的线程池是不能满⾜需求了。下⾯是ute⽅法的部分源码,可以解释上⾯的分析结果:
int c = ();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ();
}
if (isRunning(c) && workQueue.offer(command)) {
内存条怎么超频int recheck = ();
玫瑰花的样子描写
if (! isRunning(recheck) && remove(command))
reject(command);
关于冬天的诗句古诗
el if (workerCountOf(recheck) == 0)
addWorker(null, fal);
}