gpt4 book ai didi

Android:Java线程如何对应原生线程?

转载 作者:行者123 更新时间:2023-11-29 01:57:39 25 4
gpt4 key购买 nike

在 Android 中,如果我从不同的 Java 线程调用同一个 JNI 库中的函数,这些 JNI 函数是在同一个 native 线程上调用还是在不同的 native 线程中调用?

所有 Android 版本的答案都一样吗?

(我怀疑 AsyncTask 如果调用需要初始化的 JNI 库并在同一 native 线程上调用,则不是最佳选择。)

最佳答案

关于native代码,Java线程和native tread没有区别,都是一个线程。您不会通过从 Java 调用 native 方法来更改线程,它将在与之前的 Java 代码相同的线程上执行。

Java VM 为每个线程保存了一些额外的信息,因此必须先将 native 代码中创建的线程附加到 VM。

JNI 规范的以下部分给出了一些提示:

Creating the VM

The JNI_CreateJavaVM() function loads and initializes a Java VM and returns a pointer to the JNI interface pointer. The thread that called JNI_CreateJavaVM() is considered to be the main thread.

Attaching to the VM

The JNI interface pointer (JNIEnv) is valid only in the current thread. Should another thread need to access the Java VM, it must first call AttachCurrentThread() to attach itself to the VM and obtain a JNI interface pointer. Once attached to the VM, a native thread works just like an ordinary Java thread running inside a native method. The native thread remains attached to the VM until it calls DetachCurrentThread() to detach itself.

The attached thread should have enough stack space to perform a reasonable amount of work. The allocation of stack space per thread is operating system-specific. For example, using pthreads, the stack size can be specified in the pthread_attr_t argument to pthread_create.

Detaching from the VM

A native thread attached to the VM must call DetachCurrentThread() to detach itself before exiting. A thread cannot detach itself if there are Java methods on the call stack.

关于Android:Java线程如何对应原生线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14316682/

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