简体   繁体   中英

difference between android looper and executor thread pool

我正在阅读有关 loopers以及Executor Thread Pools 的内容,它们似乎在做完全相同的事情……还是我错过了什么?

A Looper manages tasks that a Thread will run. It puts them in a queue and then the Thread takes the next task in line. A Looper is tied to a specific Thread.

An Executor encapsulates managing and distributing tasks to different Threads. If you have a fixed threadpool size of 1 then I suppose it would be similar in design to a Looper because it will just queue up the work for that one Thread. If you have a threadpool with size > 1 then it will manage giving the task to the next Thread available to do the work, or in other words it will distribute tasks among all threads.

edit: Recommended reading: http://developer.android.com/reference/java/util/concurrent/package-summary.html

Executors are more flexible. For Android, the only time I really use Looper is when trying to make a Handler to communicate with the main thread from a background thread (which could even be in an ExecutorService). For example:

Handler mainThreadHandler = new Handler(Looper.getMainLooper());
mainThreadHandler.post(new Runnable...); //runs on main thread

Let me add that android looper can be used by native code. The Android Looper system is made up of the Looper class, Handler class, MesseageQueue class. One looper is bounded to one thread. From Andorid 4.0, MessageQueue is implemented by both java code and c code, which are connected. You can send a message to the same MessageQueue via native code or java code.

So the difference are:

  1. Looper is simple with one thread, however ExecutorThreadPool is complicated and flexible with one or more threads.

  2. Looper can be conveniently used by native code.

Besides, Looper and Handler is commonly used in Android code. Some android developers are more farmilar with Handler than ExecutorThreadPool.

It might be important to note that AndroidX defines HandlerExecutor . Same class is available from GMS. This is an executor that uses a Handler that can be built on any looper. For example, this way we can get an Executor for Main thread on API level < 28 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM