线程是否使用处理能力

线程是否使用处理能力

本文介绍了Android Looper 线程是否使用处理能力?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能也适用于 Java 线程的一般世​​界...

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

我有一个像这样使用的线程(这是在 run 方法中):

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();

我的问题是线程在等待将事物推送到处理程序时是否正在使用 CPU?还是真的在睡觉"?

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?

推荐答案

在幕后,Looper 是 Java 层的一个外观,用于本地代码 Looper 对象(用 C++ 编写).本机代码循环器利用了 Linux 系统调用epoll",这是一种为可扩展性而构建的 I/O 事件通知机制(即,您可以拥有大量它们而对性能影响很小——尽管会影响一些内存).这意味着当 Looper 挂在 loop() 中并且队列中没有消息时,实际上没有执行任何操作,因此它不使用处理能力(只是一点点内存).当一条消息被发布到它上面的消息队列时,线程会被唤醒"并处理该消息.

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

这篇关于Android Looper 线程是否使用处理能力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:32