Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...