2

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

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

(如果您调用需要在同一个本地线程上初始化和调用的 JNI 库,我怀疑这AsyncTask不是最佳选择。)

4

1 回答 1

1

Regarding native code, there is no distinction between Java threads and native treads, its all just a thread. You won't change the thread by calling a native method from Java, it will execute on the same thread as the Java code before.

The Java VM holds some extra information for each thread, so threads created in native code have to be attached to the VM first.

The following sections from the JNI specification give some hints:

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.

于 2013-01-14T10:35:03.803 回答