线程池与其底层源码简单分析

1、常用得四种线程池为newCachedThreadPool、newFixedThreadPool、newSingleThreadExecutor和newScheduledThreadPool 和不常用newSingleThreadScheduledExecutor 、newWorkStealingPool

使用得例子为:
线程池与其底层源码简单分析_第1张图片
经分析其底层实现方式为:
1、无界线程池 底层实现为ThreadPoolExecutor
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
其参数得意思为:
如果我们执行任务,一次启动了30个任务,由于其corePoolSize=0,所以30个任务都会被加入BlockingQueue中,然后我们新建新得线程去执行队列中得任务。如果20个任务都执行完毕。从线程闲置时开始倒计时,记时60m后关闭线程。最后线程池中的线程全部被回收并关闭。

2、有界线程池 底层实现也为ThreadPoolExecutor
具体源码为:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}

通过参数分析得:
1、corePoolSize 的数量 = nThreads    (maximumPoolSize = corePoolSize  ) 
例子:如果我们一次性执行20个任务,线程池中会启动 nThreads个线程,剩下的任务进入队列BlockingQueue。
参数  keepAliveTime = 0 ,表示某个线程任务执行完毕后,马上检查是否还有其它任务。最后 最后线程池中的线程,即使没有任务,也会保留nThreads (待验证)

3、单线程池 实现方式通过ThreadPoolExecutor

public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
//线程池中最多只有一个线程
超过1的任务,进入队列等待

4、调度线程池 底层实想ScheduledThreadPoolExecutor
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

5、单线程调度线程池
public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1, threadFactory));
}

6、public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}

你可能感兴趣的:(java)