Can my single-threaded application benefit from multiple cores? How?

Even a single-threaded application can benefit from parallel processing on different cores. For example, if your application uses a media server, then the media processing and your UI rendering application logic can run on different cores at the same time. Also, the garbage collector can run on a different core.

How can I write code that takes advantage of multiple cores?

To realize the maximum potential of the available processing power on multi-core devices, write your application with concurrency in mind. The application should be designed so that tasks which can be executed in parallel are set up to run on separate threads.

The UI Thread

In Android, the main thread is the same as the UI thread. This thread is responsible for handling all the UI events.

When you’re writing multi-threaded applications in Android, keep these things in mind about the UI thread (or main thread):

  • Only the main thread should update the UI. All other threads in the application should return data back to the main thread to update the UI.
  • There is no single point of entry in an Android application. An Android application can be entered from an Activity, Service or a Broadcast Receiver, all of which run on the UI thread.
  • Very important – The UI thread should not perform tasks that take longer than a few seconds, or else you run the risk of a sluggish user experience in your app. Read Android documentation about Keeping Your App Responsive to learn more.

As a rule of thumb, whenever your application needs to perform a longer task(s) from the UI thread, then it should parallelize using one of the parallelization techniques provided by Android: Java threads, AsyncTask or IntentService.

Parallelization technique: Java threads

The standard ways of creating threads in Java are also available in Android: extending the Thread class or implement the Runnable interface. However, if you want to pass messages to and from a thread, you need to implement message queues using android.os.Message, android.os.Handler, android.os.Looper, etc.

Also, if your application involves creating multiple threads then you might have to take care of multi-threading concurrency issues like race conditions, deadlocks and starvation. To learn more about Java threads and message passing between threads, read through the Java tutorial, Defining and Starting a Thread.

When should I use Java threads for parallelization?

When you want to parallelize tasks running longer than a few seconds, you should use Java threads from the UI thread. Android provides other, easier ways to parallelize, like AsyncTask and IntentService, so for most simple applications you may not need Java threads.

Parallelization technique: AsyncTask

AsyncTask provides the functionality to run short tasks (a couple of seconds long) in the background from the UI thread using a method called doInBackground(). You do not need to implement any message passing to and from the UI thread.  An AsyncTask uses 3 types of data:

  • Params - parameters passed to the background method as inputs.
  • Progress - data passed to the UI thread for updating progress.
  • Result - data returned from the background method upon completion.

You can implement an AsyncTask using the following steps, found in Android’s AsyncTask documentation:

  • Extend the AsyncTask class.
  • Implement the following methods:
    • onPreExecute() - performs setup like showing a progress dialog before executing the task. This method is invoked on the UI thread.
    • doInBackground(Params...) - executes all of the code that you want to run in the background and sends updates to onProgressUpdate() and the result to onPostExecute(Result). It is invoked on a pool of background threads.
    • onProgressUpdate() - invoked when publishProgress() is called from the doInBackground() method. It is invoked on the UI thread.
    • onPostExecute() - receives the return value from doInBackground(). It is invoked on the UI thread.
    • onCancelled() - invoked when cancel() is called. Invoked on the UI thread.
  • Create an instance of your extended AsyncTask class on the UI thread.
  • Call the execute() method.

Rules

  • Your extended AsyncTask class is executed by calling the execute() method, which runs on the UI thread and spawns a separate background thread to execute your task.
  • The order of execution of AsyncTask methods is: onPreExecute() -> doInBackground(Params…) -> onProgressUpdate() -> onPostExecute() or onCancelled().
  • None of the above methods can be invoked directly.
  • One instance of an AsyncTask can only be executed once. Execute should be called using multiple instances if you want to run multiple tasks.
  • An AsyncTask must be created on the UI thread.

When should I use an AsyncTask for parallelization?

Use an AsyncTask whenever you have a short background task which needs communication with the UI thread. AsyncTask is appropriate for short tasks only because it creates and manages threads for you, and you don't want to tie up resources with thread(s) that you did not create. Use Java threads and handlers from inside a service for longer-running (more than a few seconds) tasks. See the Android documentation on AsyncTask for more information.

转载:https://developer.qualcomm.com/blog/multi-threading-android-apps-multi-core-processors-part-1-2

Multi-threading Android Apps for Multi-core Processors – Part 1 of 2的更多相关文章

  1. Android apps for “armeabi-v7a” and “x86” architecture: SoC vs. Processor vs. ABI

    INSTRUCTION SET: Processors are made of semiconductor dies, usually electronic-grade mono-crystallin ...

  2. Android Apps开发环境搭建

    一 Android开发工具简介 用于Eclipse的Android开发工具(AdnroidDeveloper Tools,简称ADT)插件提供了专业级别的开发环境,利用该环境来构建AndroidApp ...

  3. Building Android Apps 30条建议

    Building Android Apps — 30 things that experience made me learn the hard way There are two kinds of ...

  4. Android Studio 3.0+ Annotation processors must be explicitly declared now

    把Android Studio 升级到3.0+ 版本的时候出现该问题:   可以看到 给了我们两种解决办法:   1. 即 给出现问题的三方 加上 annotationProcessor配置     ...

  5. Multi account chang login with multi -thread

    void worker_DoWork(object sender, DoWorkEventArgs e) { isBussy = true; if (Common.isChangingAccount) ...

  6. 创建Android Apps的30个经验教训

    这个世界上有两种人-从经验教训中学习的人以及听从别人建议的人.这里是我一路走来学到的一些东西,分享给大家: 在添加任何第三方party之前,请三思:这真的是一个成熟的项目吗? 如果一个东西用户看不到, ...

  7. Android开发训练之第五章——Building Apps with Connectivity & the Cloud

    Building Apps with Connectivity & the Cloud These classes teach you how to connect your app to t ...

  8. Multi Paxos

    Multi Paxos [2] 通过basic paxos 以上步骤分布式系统已经能确定一个值,“只确定一个值有什么用?这可解决不了我面临的问题.” 你心中可能有这样的疑问. 原simple paxo ...

  9. Android 1.5-7.0(持续更新)安全机制一览

    Android 1.5 ProPolice to prevent stack buffer overruns (-fstack-protector),在缓冲区buffer与返回地址之间加入Canary ...

随机推荐

  1. 八数码难题 双向搜索(codevs 1225)

    题目描述 Description Yours和zero在研究A*启发式算法.拿到一道经典的A*问题,但是他们不会做,请你帮他们.问题描述 在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字 ...

  2. 【HDOJ6315】Naive Operations(线段树,树状数组)

    题意: 两个序列a和b,初始a[i]=0,b[i]给定且为一个1到n的排列,要求维护以下两种操作:1.区间[L,R]内a[i]加1 2.询问[L,R]内a[i]/b[i](下取整)之和 n,q< ...

  3. castle problem——(深度优先搜索,递归实现和stack实现)

    将问题的各状态之间的转移关系描述为一个图,则深度优先搜索遍历整个图的框架为:Dfs(v) {if( v 访问过)return;将v标记为访问过;对和v相邻的每个点u: Dfs(u);}int main ...

  4. hdu 4045 Machine scheduling [ dp + 斯特林数]

    传送门 Machine scheduling Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/O ...

  5. equals() 和 hashCode()

    equals() 和 hashCode()这两个方法在java.lang.Object中,所有的类都可以继承这两个方法: 但是,这两个方法在Object类中的实现一般没什么用,所以你通常需要自己重载这 ...

  6. zoj4028 LIS

    差分约束瞎搞一下,话说这个数据不知道怎么回事,我的图按道理而言最多只有4n条边,开5n还不够??必须6n?? 约束条件首先根据f函数可建立两点之间的约束,不妨设d[i]为i到0的距离,则对于f[i] ...

  7. 删除,“windows setup 启用EMS”

    方案1[笔者推荐]:进入Windows后按Windows+R输入msconfig回车进入系统配置,切换到引导,点击你要删除的选项然后点击删除就行[1].

  8. guava缓存设置return null一直报错空指针

    guava缓存设置return null一直报错空指针 因为缓存不允许返回为空

  9. Activity调用isDestroyed()方法报出,java.lang.NoSuchMethodError

    在測试App的过程中,Activity调用了isDestroyed()方法,报出了java.lang.NoSuchMethodError错误. 自己手机MI 2S,版本号4.1.1. 事实上原因就是i ...

  10. 《The Swift Programming Language》的笔记-第27页

    页 1 type safelanguage 本页的主要内容是说swift语言是"类型检查"的安全型编程语言.意思是赋值语句的左值和右值的类型要一致,左值声明是string型变量那么 ...