Does an Android Looper thread use processing power?

你。 提交于 2021-02-08 08:23:55

问题


This question would probably also apply to the general world of Java threads...

I have a thread that I use like so (this is in the run method):

Looper.prepare();

Handler rHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        //ommited...
    }   
};

Looper.loop();

My question is whether the thread is using CPU while it's waiting for things to be pushed to the Handler? Or is it really "sleeping"?

Can having a couple of such threads bog down the system?


回答1:


Underneath the hood, Looper is a facade at the Java layer for a native code Looper object (written in C++). The native code looper takes advantage of the Linux system call "epoll", which is an I/O event notification mechanism built for scalability (i.e. you can have tons of them with little performance impact - some memory impact though). This means when a Looper is hanging out in loop() and no messages are on the queue, nothing is actually being executed, thus it doesn't use processing power (just a little bit of memory). When a message is posted to the message queue on it, the thread will be "woken up" and process the message.

If you are interested in the code, see:

AOSP_ROOT/frameworks/native/libs/utils/Looper.cpp 
AOSP_ROOT/frameworks/base/core/java/android/os/Looper.java
AOSP_ROOT/frameworks/base/core/java/android/os/MessageQueue.java
AOSP_ROOT/frameworks/base/core/jni/android_os_MessageQueue.cpp
AOSP_ROOT/frameworks/base/native/android/looper.cpp



回答2:


When the thread is waiting for a message, it is not ready to run. A thread that is not ready to run cannot use any CPU.



来源:https://stackoverflow.com/questions/8763594/does-an-android-looper-thread-use-processing-power

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!