Best use of HandlerThread over other similar classes

前端 未结 2 1980
無奈伤痛
無奈伤痛 2020-11-22 06:22

I am trying to understand the best use case of using HandlerThread.

As per definition:

\"Handy class for starting a new thread t

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 07:00

    Here is a link to the source code for HandlerThread and Looper.

    If you look at the two you will see that a HandlerThread is exactly what it says it is - a convenient way to start a Thread that has a Looper. Why does this exist? Because threads, by default do not have a message loop. The HandlerThread is just an easy way to create one that does. Could you duplicate this function with Handler, Thread, and Looper - judging from the source code - the answer is yes.

    An Executor is different. An Executor takes submitted runnable tasks and - guess what -executes them. Why is this necessary? It allows you to decouple the execution of the task from its actual substance. When would you use this? Say you had a situation that required executing multiple tasks at the same time. You could choose, using an Executor, to run them all on a single thread so that they are executed serialy. Or you could use a fixed thread pool so that some, but not all are run at the same time. In either case the substance of the task - i.e. what it's actually doing - is seperate from the manner in which it is being executed.

提交回复
热议问题