Android Looper 线程是否使用处理能力?
这个问题可能也适用于 Java 线程的一般世界......
我有一个像这样使用的线程(这是在 run
方法中):
Looper.prepare();
Handler rHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
//ommited...
}
};
Looper.loop();
我的问题是线程是否正在使用 CPU当它等待东西被推送到处理程序时?还是真的在“睡觉”?
拥有几个这样的线程会使系统陷入困境吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在底层,Looper 是本机代码 Looper 对象(用 C++ 编写)的 Java 层的外观。本机代码循环程序利用 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:
当线程等待消息时,它还没有准备好运行。未准备好运行的线程无法使用任何 CPU。
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.