惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
阮一峰的网络日志
阮一峰的网络日志
云风的 BLOG
云风的 BLOG
D
Docker
Vercel News
Vercel News
IT之家
IT之家
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
V
Visual Studio Blog
Engineering at Meta
Engineering at Meta
腾讯CDC
Google DeepMind News
Google DeepMind News
I
InfoQ
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
The GitHub Blog
The GitHub Blog
博客园 - Franky
The Cloudflare Blog
A
About on SuperTechFans
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
T
Tenable Blog
P
Proofpoint News Feed
Recorded Future
Recorded Future
Security Latest
Security Latest
H
Hackread – Cybersecurity News, Data Breaches, AI and More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 聂微东
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google Online Security Blog
Google Online Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
U
Unit 42
The Hacker News
The Hacker News
Martin Fowler
Martin Fowler
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
F
Full Disclosure
M
MIT News - Artificial intelligence
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
V
V2EX
Project Zero
Project Zero

博客园 - 和尚释然

Android 模拟器截图 [原创]Android NDK开发之HelloWorld 附源码 Android NDK开发之环境搭建 [原创]深入了解Activity生命周期 附源码 [原创]关于Android Service的示例编程 附源码 [原创]Android Camera 开发之实现一 附源码 [原创]Android Camera 开发之前言 [原创]在Eclipse中手工安装SVN Plugin Android开发环境搭建四:新建一台Android Virtual Device Android开发环境搭建三:在Eclipse配置Android SDK Android开发环境搭建二:安装ADT[新版本ADT15.0] Android开发环境搭建一:安装Android JDK Java开发环境配置图解 用Reflector反编译 Mobile Winform程序 Mobile WiFi的开启和关闭代码实现 VS2005/VS2008英文版应用程序无法显示中文字符 深入讲解main()返回值研究 用VisualStudio2008汇编代码 发布MFC ActiveX控件并实现自动更新
AsyncTask原理
和尚释然 · 2013-05-24 · via 博客园 - 和尚释然

2013-05-24 13:52  和尚释然  阅读(480)  评论()    收藏  举报

AsyncTask的基本原理是创建一个线程池,通过线程池执行一个Runnable对象(FutureTask),然后通过Handler通知UI线程。

1、线程池的创建。创建线程池,并返回一个执行器对象(Executor)

[java] viewplaincopy

  1. private static final int CORE_POOL_SIZE = 5;
  2. private static final int MAXIMUM_POOL_SIZE = 128;
  3. private static final int KEEP_ALIVE = 10;
  4. private static final BlockingQueue<Runnable> sWorkQueue =
  5. new LinkedBlockingQueue<Runnable>(10);
  6. private static final ThreadFactory sThreadFactory = new ThreadFactory() {
  7. private final AtomicInteger mCount = new AtomicInteger(1);
  8. public Thread newThread(Runnable r) {
  9. return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
  10. }
  11. };
  12. private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
  13. MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

2、将被执行的Runnable对象(FutureTask)的创建。在构造方法中创建FutureTask。

[java] viewplaincopy

  1. public AsyncTask() {
  2. mWorker = new WorkerRunnable<Params, Result>() {
  3. public Result call() throws Exception {
  4. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
  5. return doInBackground(mParams);
  6. }
  7. };
  8. mFuture = new FutureTask<Result>(mWorker) {
  9. @Override
  10. protected void done() {
  11. Message message;
  12. Result result = null;
  13. try {
  14. result = get();
  15. } catch (InterruptedException e) {
  16. android.util.Log.w(LOG_TAG, e);
  17. } catch (ExecutionException e) {
  18. throw new RuntimeException("An error occured while executing doInBackground()",
  19. e.getCause());
  20. } catch (CancellationException e) {
  21. <span style="color:#ff0000;"> </span>message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
  22. new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
  23. message.sendToTarget();
  24. return;
  25. } catch (Throwable t) {
  26. throw new RuntimeException("An error occured while executing "
  27. + "doInBackground()", t);
  28. }
  29. message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
  30. new AsyncTaskResult<Result>(AsyncTask.this, result));
  31. message.sendToTarget();
  32. }
  33. };
  34. }

其中WorkRunnable是一个Callable对象:

[java] viewplaincopy

  1. private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
  2. Params[] mParams;
  3. }

3、执行,execute方法。

[html] viewplaincopy

  1. public final AsyncTask<Params, Progress, Result> execute(Params... params) {
  2. if (mStatus != Status.PENDING) {
  3. switch (mStatus) {
  4. case RUNNING:
  5. throw new IllegalStateException("Cannot execute task:"
  6. + " the task is already running.");
  7. case FINISHED:
  8. throw new IllegalStateException("Cannot execute task:"
  9. + " the task has already been executed "
  10. + "(a task can be executed only once)");
  11. }
  12. }
  13. mStatus = Status.RUNNING;
  14. onPreExecute();
  15. mWorker.mParams = params;
  16. sExecutor.execute(mFuture);
  17. return this;
  18. }

4、使用Handler通知UI线程,在上面的第二步中最后两行代码。