目录
2:底层都是通过new ThreadPoolExecutor来实现的
线程池实现原理
1:使用工具类Executors来生成各种不同线程池
2:底层都是通过new ThreadPoolExecutor来实现的
3:核心方法
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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
几种线程池的测试(附加测试结果)
1:newFixedThreadPool
底层使用的阻塞队列是 LinkedBlockingQueue<Runnable>()
/**
* newFixedThreadPool
* 固定大小线程池
*/
@Test
public void testFix(){
ExecutorService threadPool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "\t 工作");
}
});
}
}
结果: 最多会出现3个
pool-1-thread-1 工作
pool-1-thread-2 工作
pool-1-thread-3 工作
pool-1-thread-1 工作
pool-1-thread-2 工作
pool-1-thread-3 工作
pool-1-thread-1 工作
pool-1-thread-3 工作
pool-1-thread-2 工作
pool-1-thread-1 工作
2:newSingleThreadExecutor
底层使用的阻塞队列是 LinkedBlockingQueue<Runnable>()
/**
* newSingleThreadExecutor
* 1个大小线程池
*/
@Test
public void testSingle(){
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for (int i = 1; i <= 10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "\t 工作");
}
});
}
}
结果: 永远只有一个线程在工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
pool-1-thread-1 工作
3:newCachedThreadPool
底层使用的阻塞队列是 SynchronousQueue<Runnable>()
/**
* newCachedThreadPool
* 自适应大小线程池
*/
@Test
public void testCached(){
ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 1; i <= 20; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "\t 工作");
}
});
}
}
结果:工作线程的数量是可以自适应扩展的,读者可以调整任务个数进行测试
pool-1-thread-1 工作
pool-1-thread-2 工作
pool-1-thread-3 工作
pool-1-thread-2 工作
pool-1-thread-1 工作
pool-1-thread-3 工作
pool-1-thread-2 工作
pool-1-thread-3 工作
pool-1-thread-2 工作
pool-1-thread-3 工作
pool-1-thread-3 工作
pool-1-thread-3 工作
pool-1-thread-1 工作
pool-1-thread-2 工作
pool-1-thread-1 工作
pool-1-thread-2 工作
pool-1-thread-1 工作
pool-1-thread-2 工作
pool-1-thread-3 工作
pool-1-thread-1 工作
执行完需要手动关闭线程池
threadPool.shutdown();
java线程池详细讲解理论篇(一) https://blog.csdn.net/weixin_45191798/article/details/100153524