最近,我研究了Android系统中的Handler
类。在我看来,Handler
机制是Thread
运行一个死循环并在该死循环中重复从队列中检索消息,然后将消息发送到目标处理程序。
但是当队列中没有消息时,必须在指定的时间内等待或阻塞线程,这可以减少CPU时间。我的理解是,为了在指定的时间内等待或阻止Thread
,它使用linux epoll函数在本机层中等待指定的时间。然后,当队列中有消息时,它使用linux管道唤醒线程。
所以我的困惑是为什么Android系统使用Linux进程通信函数(IPC)来控制Java Thread
等待或唤醒? Java Thread
与系统线程或linux线程之间的关系是什么?
换句话说,我真正想知道的是为什么android使用linux ipc函数来控制java线程来实现所谓的Handler,它用于在java线程之间发送消息。
以下是relevant code from the Android platform
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycle();
}
}
答案 0 :(得分:1)
在阅读完问题后,我的好奇心引导我this。我相信使用 Linux进程通信函数(IPC)来控制 Java线程存在误解。
我不相信我能更好地解释链接中给出的漂亮描述。