Android NDK c建立新的线程

在jni的c/c++层建立一个新的线程只须要3步:java

1.导入库c++

#include<pthread.h>ide

2.写好线程要作的事spa

void* run_1(void*);线程

void* run_1(void* args){翻译

...指针

}orm

3.调用方法接口

pthread_t thread_1;ci

pthread_create(&thread_1,NULL,run_1,args);

///////////////////////////////////////////////////////////////////////////////////

可是这样的线程,缺乏了JNIEnv指针,好像干不了什么事,因此就要作这个基础上,获得JNIEnv指针,并将该线程依附于java虚拟机之上,这样这个线程像java层过来的线程同样,可以干不少事情。

官方文档关于attachCurrentThread()的说明,好像勉强看得懂,就翻译一下试试。。。

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 thepthread_attr_t argument to pthread_create.

JNI接口的JNIEnv指针只是在当前线程是有效的(意思是不一样的线程不能共用一个JNIEnv*)。其余的线程要访问虚拟机的时候,他就必须经过调用AttachCurrentThread()方法来让当前线程与虚拟机创建某种关系,而后获得一个指针,也就是JNIEnv*。这个线程一旦与了虚拟机创建了某种关系,这个本地(由c/c++代码建立)的线程就可以像一个一般的java线程同样在c/c++层执行了。这种关系一直保持着,直到他调用了DetachCurrentThread()方法来解除关系。
这个与vm保持着某种关系的线程必需要保证有足够的栈空间来执行各类工做。每一个线程所能分配的栈空间大小是有明确规定的。举个例子,使用了pthreads,栈的大小就应该是在pthread_create方法调用时传入的pthread_attr_t参数(第二个参数)的大小以内。(这里正好说明了以上方法的第二个参数是干吗的,null估计就默认分配了)
 

例子代码见原帖.

相关文章
相关标签/搜索