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

3
最近,我研究了Android系统中的Handler类。在我看来,Handler机制是指Thread在一个死循环中重复地从队列中检索消息,然后将消息发送到目标处理程序。
但是当队列中没有消息时,线程必须等待或阻塞一段时间,这可以减少CPU时间。我的理解是,为了等待或阻塞线程一段时间,它使用Linux epoll函数在本地层等待指定的时间。然后,它使用Linux管道在有消息时唤醒线程。
因此,我的困惑是:为什么Android系统使用Linux进程通信函数(IPC)来控制Java线程等待或唤醒?Java线程与系统线程或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();
        }
    }

3
为什么会有那么多人踩这个问题?在我看来,这是一个完全合理的问题。我给你点赞来抵消一些踩的票数。 - Simon
@Simon,感谢您的支持。 - KrystalJake
@Simon,这些踩票表明这个问题很难理解。如果你认为这是一个好问题,那么编辑问题有助于让其他人看到。仅仅评论并不能(总是)起到作用。 - Boris the Spider
我真的很想知道JVM中的线程与Linux线程或系统线程之间的关系,以及在Linux系统中对应于Java线程的是什么?为什么Android可以使用Linux IPC和epoll通过JNI控制Java线程在本地被等待或阻塞。 - KrystalJake
1个回答

1
阅读您的问题后,我好奇地点击了this。我认为有关使用 Linux进程通信函数(IPC)来控制 Java线程的误解。

在链接中给出的美丽描述已经很好地解释了,我无法更好地解释它。

Android进程的通信机制


提供的文章非常好,让我理解了Android平台。但我真正想知道的是为什么Android使用Linux IPC函数来控制Java线程,以实现所谓的Handler,用于在Java线程之间发送消息。 - KrystalJake
@KrystalJake 我不是安卓用户,只是因为好奇才研究了一下。希望我们很快能得到更好的答案,让我们再给它一些时间。 - Dileep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接