线程池ThreadPoolExecutor的使用Demo

您所在的位置:网站首页 java调用demo 线程池ThreadPoolExecutor的使用Demo

线程池ThreadPoolExecutor的使用Demo

2024-07-15 22:40| 来源: 网络整理| 查看: 265

由于阿里开发手册提出禁用Executor创建线程池,主要原因是容易引起OOM,推荐使用ThreadPoolExecutor,自己手动创建线程池,根据实际情况设置核心线程数,防止OOM

public class ThreadTest { /** * ThreadPoolExecutor使用 */ public static void main(String[] args) throws InterruptedException, IOException { //核心线程池大小 int corePoolSize = 2; //最大线程池大小 int maximumPoolSize = 4; //线程最大空闲时间 long keepAliveTime = 10; //时间单位 TimeUnit unit = TimeUnit.SECONDS; //线程等待队列 BlockingQueue workQueue = new ArrayBlockingQueue(2); //线程创建工厂 ThreadFactory threadFactory = new NameTreadFactory(); //拒绝策略 RejectedExecutionHandler handler = new SelfIgnorePolicy(); //创建线程(根据实际情况确定核心线程池大小) ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); //预启动所有核心线程 executor.prestartAllCoreThreads(); for (int i = 1; i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3