Java正确创建线程池方式

来源:互联网 发布:python 迭代器 定义 编辑:程序博客网 时间:2024/05/21 06:42

  PS:最近换工作,被问到多次线程池的问题 例如 线程池的几种实现方式,怎样创建一个线程池等等。也是前段时间阿里发布了Java代码约束工具,规定不建议使用Executors去直接创建线程,而是通过ThreadPoolExcutor的方式,规则如下:

线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资激耗尽的风险。
说明:Executors各个方法的弊端:
1) newFixedThreadPoolfPnewSingleThreadExecutor:
主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至00M。
2) newCachedThreadPoolfPnewScheduledThreadPool:
主要问題是线程数最大数是Integer.MAX_VALUE,可能会创建数置非常多的线程,甚至00M。

Positive example 1:

//org.apache.commons.Iang3.concurrent.BasicThreadFactoryScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(l,          new BasicThreadFactory.Builder().namingPattern(Mexample-schedule-pool-%d").daemon(true).build());
Positive example 2:

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(Mdemo-pool-%d").build();//Common Thread PoolExecutorService pool = new ThreadPoolExecutor(5, 200,   0L, TimeUnit.MILLISECONDS,   new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());pool.execute(()-> System.out.println(Thread.currentThread().getName()));pool.shutdown() "/gracefully shutdown
Positive example 3:

<bean id="userThreadPoolMclass="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"><property name=McorePoolSize" value="10M /><property name=MmaxPoolSize" value="100M /><property name=MqueueCapacity" value="2000M /><property name=MthreadFactoryM value= threadFactory /><property name="rejectedExecutionHandlerM><ref local="rejectedExecutionHandler" /></property></bean>//in codeuserThreadPool.execute(thread);

原创粉丝点击