What is the different between Handler, Runnable, and Threads?

Hong Wei Wang picture Hong Wei Wang · Jan 17, 2014 · Viewed 29.8k times · Source

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?

  1. What is the point of Runnable if one can write the background code in the Thread's run method?
  2. How is Handler used inside thread and why do we need to use it.
  3. Android has another thing call runOnUiThread, How do we use that? I know that it is used for updating the UI.

Answer

William Morrison picture William Morrison · Jan 17, 2014

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?

  • 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.