Why use Runnable over Thread?
-
Runnable
separates code that needs to run asynchronously, from how the code is run. This keeps your code flexible. For instance, asynchronous code in a runnable can run on a threadpool, or a dedicated thread.A
Thread
has state your runnable probably doesn’t need access to. Having access to more state than necessary is poor design.Threads occupy a lot of memory. Creating a new thread for every small actions takes processing time to allocate and deallocate this memory.
What is runOnUiThread actually doing?
-
Android’s runOnUiThread queues a
Runnable
to execute on the UI thread. This is important because you should never update UI from multiple threads.runOnUiThread
uses aHandler
.Be aware if the UI thread’s queue is full, or the items needing execution are lengthy, it may be some time before your queued
Runnable
actually runs.
What is a Handler?
- A handler allows you to post runnables to execute on a specific thread. Behind the scenes, runOnUi Thread queues your
Runnable
up with Android’s Ui Handler so your runnable can execute safely on the UI thread.