繁体   English   中英

Java线程和系统线程之间有什么关系

[英]What's the relationship between java thread and system thread

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

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

所以我的困惑是, 为什么Android系统使用Linux进程通信功能(IPC)来控制Java Thread等待还是唤醒? Java Thread与系统线程或linux线程之间有什么关系

换句话说,我真正想知道的是为什么android使用linux ipc函数来控制java线程来实现所谓的Handler,该Handler用于在java线程之间发送消息。

这是来自Android平台相关代码

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

看完你的问题后,我的好奇心使我明白了这一点 而且我相信使用Linux进程通信功能(IPC)来控制Java Thread会有误解。

我不相信我能用链接中给出的美丽描述更好地解释它。

Android进程的通讯机制

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM