First article of a new series about Android Fundamentals in which I’d like to touch on some grounds of Android operating system.
1. Way of thinking about the threads
Basically, computer program is a sequence of instructions which are processed and then executed by central processing unit. So, how do threads fit in here?
Thread can be identified as a code path of program execution.
2. Single-Threaded vs. Multithreaded application
In single-threaded applications all instructions are executed sequentially, one by one. In other words, using previously introduced concept, there is only one code path. This approach has one major flaw – instructions have to wait for preceding instructions to be executed. It may result in slowdown or even ANR (Application Not Responding) errors.
In multithreaded applications code is split into few code paths. It is worth noting that if number of executing threads is greater than number of processors then application can’t be truly concurrent.
Code path concept was taken from ‘Efficient Android Threading’ by Anders Goransson.
3. Android UI thread mystery
We triggered an application, application instance was created, eventually all user interface components were drawn on the screen. All right, but how come after all these operations UI thread didn’t terminate and is still waiting for user actions? Why UI components are still visible on the screen?
4. Loopers to the rescue
Loopers are the missing part! They transform normal threads into continuously running threads. If thread is looped, JVM won’t terminate it (unless it is a daemon thread).
Note that only UI thread has looper by default.
In custom threads it’s necessary to associate looper with thread explicitly.
5. Communication with threads
Let’s say we want to communicate with our UI thread from some concurrent, background thread. I will touch on this in my next article: Android Fundamentals: Magic of threads – Handlers and Message Queues. Stay tuned!