What is the difference between Handler, Runnable, and Threads?
While I was working with android, and I need something to run in the background. I use Threads to run it. Usually I would write a class that extends Thread and implement the run method.
I have also saw some examples that implments runnable and pass into runnable into Threads.
However I am still confused. Can someone give me a clear explanation?
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 a Handler
.
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?
Runnable
up with Android's Ui Handler so your runnable can execute safely on the UI thread.