android使用Executors创建线程池的弊端
2017-11-01 11:27
483 查看
线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。 说明:Executors各个方法的弊端: 1)newFixedThreadPool和newSingleThreadExecutor: 主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。 2)newCachedThreadPool和newScheduledThreadPool: 主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。
正确的写法案例: Positive example 1: //org.apache.commons.lang3.concurrent.BasicThreadFactory ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
Positive example 2: ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("demo-pool-%d").build(); //Common Thread Pool ExecutorService 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="userThreadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="10" /> <property name="maxPoolSize" value="100" /> <property name="queueCapacity" value="2000" /> <property name="threadFactory" value= threadFactory /> <property name="rejectedExecutionHandler"> <ref local="rejectedExecutionHandler" /> </property> </bean> //in code userThreadPool.execute(thread);
相关文章推荐
- Executors与ThreadPoolExecutor(阿里发布的 Java开发手册中强制线程池不允许使用 Executors 去创建)
- Java 使用Executors创建线程池
- 线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
- 线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式
- Executors创建的4种线程池的使用
- Java(Android)线程池,介绍new Thread的弊端及Java四种线程池的使用
- android 线程池的使用以及Executors的优缺点
- 线程池不使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式
- Android线程池(一)——Executors(线程池)以及FutureTask使用示例
- Android线程池:ExecutorService和Executors使用
- Executors创建的4种线程池的使用
- android 多线程 - 线程池 Executors.newFixedThreadPool 的使用例子
- Executors创建的4种线程池的使用
- 4000 Executors创建的4种线程池的使用
- Android线程池(一)——Executors(线程池)以及FutureTask使用示例
- Executors创建线程池的弊端
- android中,用SimpleAdapter创建有自己布局的listView,以及listView的修改更新notifyDataSetChanged()的使用。
- android自定义控件的创建和使用
- 创建和使用Android library工程
- 在Android中创建和使用数据库