首页 > 代码库 > Java AsyncTask 分析内部实现
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 线程池
[java] view plaincopyprint?
- 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;
- }
[java] view plaincopyprint?
- 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 线程池
SerialExecutor ,使用同步锁,一次执行一个线程[java] view plaincopyprint?- 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;
- }
THREAD_POOL_EXECUTOR 并发线程池[java] view plaincopyprint?- 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); //可以自定义 线程池 使用这两种方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。