What is the difference between a Thread and a Handler

前端 未结 3 1178
故里飘歌
故里飘歌 2021-02-05 07:08

I\'m trying to find out the difference between a thread and a handler. Does creating a new handler create a new thread?. When a new handler is run using post(), is it creating a

相关标签:
3条回答
  • 2021-02-05 07:24

    A thread defines a process running. Like you have a main (UI thread) in android. and all other threads run in background.(in parallel).

    Handler is completely different, it is like initiating the task defined in a handler..

    To clear out your confusion, and perform threading in android you must read : http://android-developers.blogspot.com/2009/05/painless-threading.html

    and i would suggest AsyncTask instead of using Thread in all cases.

    0 讨论(0)
  • 2021-02-05 07:31

    Threads are generic processing tasks that can do most things, but one thing they cannot do is update the UI.

    Handlers on the other hand are bound to threads that allow you to communicate with the UI thread (update the UI).

    So for example show a toast or a update a progress bar via a message (Runnable) posted to a handler but you can't if you start this runnable as a thread.

    With handler you can also have things like MessageQueuing, scheduling and repeating.

    I am yet to encounter a situation where I needed a thread in android.

    I mostly use a combination of AsyncTasks and Handlers.

    Handlers for the aforementioned tasks.

    AsyncTasks for download/ data fetching and polling etc.

    You can read the developer article here "Painless Threading" for more threading in android.

    Correction: Each Handler instance is associated with a single thread and that thread's message queue. They are not threads in their own behalf. as described here.

    0 讨论(0)
  • 2021-02-05 07:32

    Why we use handlers with thread :

    When we install an application in android then it create a thread for that application called MAIN UI Thread, All activities run inside that thread , By the android single thread model rule we can not access UI elements (bitmap , textview etc..) directly for another thread defined inside that activity.

    So if want to access Main UI Thread elements by another thread then we will use handlers.

    0 讨论(0)
提交回复
热议问题