Java多线程为什么使用线程池?以及工作原理
•技术分享
854 0
Executors
, ThreadPoolExecutor
)使用 Executors
的工厂方法:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
使用 ThreadPoolExecutor
创建线程池:
int corePoolSize = 5;
int maximumPoolSize = 10;
long keepAliveTime = 1L;
TimeUnit unit = TimeUnit.MINUTES;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(50);
ThreadFactory threadFactory = Executors.defaultThreadFactory();
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory,
handler
);
corePoolSize
: 核心线程数,这是默认情况下线程池维护的线程数量。maximumPoolSize
: 最大线程数,当队列满了,且核心线程都在工作,线程池可以创建新线程,直到达到这个最大值。keepAliveTime
& unit
: 当工作线程数量超过核心线程数量时,多余的线程会等待这个时间后,如果仍然空闲,就会被终止。workQueue
: 用于保存等待执行的任务的阻塞队列。threadFactory
: 用于创建新线程的工厂。handler
: 当队列和最大线程数都满了后,新提交的任务如何被处理的策略。这是关于Java线程池的基本概念和代码示例。在真实环境中,建议避免使用 Executors
的默认方法创建线程池,因为它们往往不满足特定的需求,最好自定义参数并使用 ThreadPoolExecutor
。
版权属于:戏人看戏博客网
本文链接:https://day.nb.sb/archives/1349.html
若无注明均为戏人看戏原创,转载请注明出处,感谢您的支持!