What are the advantages / reasons to use a Handler and not a Thread?
A Handler allows you to send and process Message and Runnable
objects associated with a thread's MessageQueue
. Each Handler
instance is associated with a single thread and that thread's message queue.
When you create a new Handler
, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler:
- To schedule messages and Runnables to be executed as some point in the future
- To enqueue an action to be performed on a different thread than your own.
If you use java threads, you have to handle somethings on your own - synchronizing with main thread, cancelling a thread etc.
This single Thread does not create a thread pool unless you use ThreadPoolExecutor
or ExecutorService
API.
(Taken this query from your comments on Blackbelt answer)
Why not use an Executor? and even if I did want to use a Handler to do that, how?
Reference : Thread Performance article
There are certain types of work that can be reduced to highly parallel, distributed tasks. With the sheer volume of work packets this creates, AsyncTask
and HandlerThread
aren’t appropriate classes. The single-threaded nature of AsyncTask
would turn all the threadpooled work into a linear system. Using the HandlerThread
class, on the other hand, would require the programmer to manually manage load balancing between a group of threads.
ThreadPoolExecutor is a helper class to make this process easier. This class manages the creation of a group of threads, sets their priorities, and manages how work is distributed among those threads. As workload increases or decreases, the class spins up or destroys more threads to adjust to the workload.
BlockingQueue workQueue= new LinkedBlockingQueue<Runnable>(100); // Work pool size
ThreadPoolExecutor executor = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(), // Initial pool size
Runtime.getRuntime().availableProcessors(), // Max pool size
1, // KEEP_ALIVE_TIME
TimeUnit.SECONDS, // KEEP_ALIVE_TIME_UNIT
workQueue);
You can refer to this developer guide article on create-threadpool for more details.
Have a look at this post for usage of Handler
to run multiple Runnable instances. In this case, all Runnable
tasks will run in a single Thread.
Android: Toast in a thread