阿里巴巴Android开发手册
【强制】新建线程时,必须通过线程池提供(AsyncTask 或者 ThreadPoolExecutor或者其他形式自定义的线程池),不允许在应用中自行显式创建线程
说明:
使用线程池的好处是减少在创建和销毁线程上所花的时间以及系统资源的开销,解决资源不足的问题。
如果不使用线程池,有可能造成系统创建大量同类线程而导致消耗完内存或者“过度切换”的问题。另外创建匿名线程不便于后续的资源使用分析,对性能分析等会造成困扰。
正例:
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); int KEEP_ALIVE_TIME = 1; TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS; BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>(); ExecutorService executorService = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES*2, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, taskQueue, new BackgroundThreadFactory(), new DefaultRejectedExecutionHandler()); //执行任务 executorService.execute(new Runnnable() { ... });
反例:
new Thread(new Runnable() { @Override public void run() { //操作语句 ... } }).start();
扩展参考:
https://blog.mindorks.com/threadpoolexecutor-in-android-8e9d22330ee3
【强制】线程池不允许使用 Executors 去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险.
说明:
Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool : 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM;
2) CachedThreadPool 和 ScheduledThreadPool : 允许的创建线程数量 为Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
正例:
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); int KEEP_ALIVE_TIME = 1; TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS; BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>(); ExecutorService executorService = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES*2, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, taskQueue, new BackgroundThreadFactory(), new DefaultRejectedExecutionHandler());
反例:
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
扩展参考:
http://dev.bizo.com/2014/06/cached-thread-pool-considered-harmlful.html
【推荐】ThreadPoolExecutor 设置线程存活时间(setKeepAliveTime),确保空闲时线程能被释放
参考:
Java线程池ThreadPoolExecutor详解
http://www.crazyant.net/2124.html
深入理解java线程池—ThreadPoolExecutor
https://www.jianshu.com/p/ade771d2c9c0
JAVA多线程机制
http://www.cnblogs.com/lijunamneg/archive/2013/03/22/2976050.html