gpt4 book ai didi

java - java线程和系统线程有什么关系

转载 作者:太空狗 更新时间:2023-10-29 12:32:53 25 4
gpt4 key购买 nike

最近在研究Android系统中的Handler类。在我看来,Handler 机制是Thread 运行一个死循环,并在死循环中反复从队列中检索消息,然后将消息发送给目标处理程序。

但当队列中没有消息时,线程必须等待或阻塞指定的时间,这可以减少 CPU 时间。我的理解是为了让Thread等待或阻塞指定的时间,它在native层使用了linux epoll函数来等待指定的时间。然后,当队列中有消息时,它使用 linux 管道唤醒线程。

所以我的困惑是为什么Android系统使用Linux进程通信函数(IPC)来控制JavaThread等待或唤醒?还有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();
}
}

最佳答案

阅读您的问题后,我的好奇心将我引向了this .我相信对于使用 Linux 进程通信函数 (IPC) 来控制 Java 线程 存在误解。

我不相信我能比链接中给出的漂亮描述更好地解释它。

Communication Mechanism of Android Processes

关于java - java线程和系统线程有什么关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com