Java AsyncTask 分析内部实现
sdk3.0前,使用内部的线程池,多线程并发执行。线程池大小等于5,最大达128
sdk3.0后,使用默认的serial线程池,执行完一个线程,再顺序执行下一个线程。sdk4.3时 线程池大小等于5,最大达128
sdk4.4后线程池大小等于 cpu count + 1,最大值为cpu count * 2 + 1
sdk3.0后有两种线程池的实现,默认为 Serial 线程池
- public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
- public static final Executor THREAD_POOL_EXECUTOR
- = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
- TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
- private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
- public static void setDefaultExecutor(Executor exec) {//设置默认线程池
- sDefaultExecutor = exec;
- }
- private static class SerialExecutor implements Executor {
- final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
- Runnable mActive;
- public synchronized void execute(final Runnable r) {
- mTasks.offer(new Runnable() {
- public void run() {
- try {
- r.run();
- } finally {
- scheduleNext();
- }
- }
- });
- if (mActive == null) {
- scheduleNext();
- }
- }
- protected synchronized void scheduleNext() {
- if ((mActive = mTasks.poll()) != null) {
- THREAD_POOL_EXECUTOR.execute(mActive);
- }
- }
- }
-
sdk3.0前,使用内部的线程池,多线程并发执行。线程池大小等于5,最大达128
sdk3.0后,使用默认的serial线程池,执行完一个线程,再顺序执行下一个线程。sdk4.3时 线程池大小等于5,最大达128
sdk4.4后线程池大小等于 cpu count + 1,最大值为cpu count * 2 + 1
sdk3.0后有两种线程池的实现,默认为 Serial 线程池
- public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
- public static final Executor THREAD_POOL_EXECUTOR
- = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
- TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
- private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
- public static void setDefaultExecutor(Executor exec) {//设置默认线程池
- sDefaultExecutor = exec;
- }
- private static class SerialExecutor implements Executor {
- final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
- Runnable mActive;
- public synchronized void execute(final Runnable r) {
- mTasks.offer(new Runnable() {
- public void run() {
- try {
- r.run();
- } finally {
- scheduleNext();
- }
- }
- });
- if (mActive == null) {
- scheduleNext();
- }
- }
- protected synchronized void scheduleNext() {
- if ((mActive = mTasks.poll()) != null) {
- THREAD_POOL_EXECUTOR.execute(mActive);
- }
- }
asynctask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //设置使用 并发线程池
asynctask.executeOnExecutor(executor); //可以自定义 线程池 使用这两种方法
THREAD_POOL_EXECUTOR 并发线程池
asynctask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //设置使用 并发线程池
asynctask.executeOnExecutor(executor); //可以自定义 线程池 使用这两种方法
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。