我在想,handlerthread可以实现异步处理消息,还是批量的。多线程也是异步,处理批量消息。那么这两者的区别呢。
想了想,其实这两者的区别是很大的,多线程注重的并发,可以有多个线程,或者引入线程池进行管理。但是HandlerThread如果是new一个,那么它就是一个线程,一个线程处理多个消息。
还有一个区别,handlerthread的run方法里面是死循环,也就是除非手动调用quit方法线程是不会退出的,而多线程的线程有各自的处理方式,没有固定。
所以,我认为handlerthread适合后台处理一些零散的消息,他的存活周期由你决定。而多线程更注重并发,当然也要考虑实际资源情况,用线程池的话也可以达到后台批处理消息,各种消息,当然开销会大一些。
HandlerThread is simpler than than ExecutorService. So it will use less resources and work faster. So if you have a lot of small messages process them via Handler.
But Executors it’s not just a class. Executors is a standart. It’s a framework with a lot of features and every java programmer can understand your code written with executors. A lot of libraries can work with executors. It’s flexible, you can easily change executor type or executor queue. So if you have a complex processing task and you do not know how exactly implement it use executors.