【发布时间】:2014-02-11 08:02:49
【问题描述】:
最近研究了Android系统中的Handler类。在我看来,Handler 机制是Thread 运行一个死循环并在该死循环中重复从队列中检索消息,然后将消息发送到目标处理程序。
但是当队列中没有消息时,线程必须等待或阻塞指定时间,这样可以减少CPU时间。我的理解是,为了等待或阻塞Thread指定时间,它使用linux epoll函数在native层等待指定时间。然后,当队列中有消息时,它使用 linux 管道唤醒线程。
所以我的困惑是为什么Android系统使用Linux进程通信功能(IPC)来控制JavaThread等待或唤醒?以及JavaThread与系统线程或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();
}
}
【问题讨论】:
-
为什么所有的反对票?对我来说,这似乎是一个完全有效的问题。有一个 +1 取消其中一些。
-
@Simon,感谢您的支持。
-
@Simon 否决票表明这个问题很难理解。如果您认为这是一个好问题,那么它有助于编辑问题,以便其他人可以看到。仅仅发表评论并不能(总是)起到作用。
-
我很想知道jvm中的线程和linux线程或者系统线程是什么关系,linux系统中java线程对应的是什么?为什么Android可以使用linux IPC和epoll来控制java JNI 在本机中等待或阻塞的线程。