how does multithreading increases performance of an app?
Generally speaking, it does not increase the performance of an app. It may solve specific problems in terms of UX, such as decreasing jank.
In my knowledge, a process/app is assigned a single thread by the OS.
No, an Android app will have several threads at the outset, created by the framework. These include the main application thread and a pool of binder threads.
If you create multiple threads inside that process, those threads aren't like a whole new batch of threads assigned to the process by OS.
Yes, they are.
Instead one thread executes at a time while the other thread is waiting.
On a multi-core CPU, multiple threads can truly execute in parallel. Even on single-core CPUs, the Linux scheduler (part of the Linux kernel at the heart of Android) will time-slice between threads.
Example regarding non UI threads & UI threads will be very helpful.
The main application thread (a.k.a., UI thread) is, at its core, just a thread. However, it is the thread that is responsible for dispatching key and touch events and otherwise applying UI updates. It is important not to block that thread, and so if you are running on that thread (e.g., onCreate()
of activities and fragments, onClick()
of a widget, getView()
in a ListAdapter
), you need to return very quickly, ideally in well under a millisecond. Otherwise, you have "jank", defined in Android as being a frozen UI, particularly while the UI should be animating (e.g., scrolling a ListView
).
So, for example, let's suppose that we want to download a file, one big enough that it will take 10 seconds to download. Whether we download the file on the main application thread or on a background thread does not impact overall performance, as it will take 10 seconds either way. However, downloading on the main application thread would freeze our UI for 10 seconds, which will make users unhappy. Downloading the file on a background thread avoids this problem. Note that trying to do network I/O on the main application thread fails by default on Android 4.0+ (with a NetworkOnMainThreadException
), specifically to avoid this particular problem.