JavaVM 代表的是Java虛擬機博个,所有的工作都是從JavaVM開始
可以通過JavaVM獲取到每個線程關(guān)聯(lián)的JNIEnv
如何獲取JavaVM春缕?
- 在JNI_OnLoad函數(shù)中獲取
- (*env)->GetJavaVM(env,&javaVM);
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved){
LOGI("%s","JNI_OnLoad");
javaVM = vm;
return JNI_VERSION_1_4;
}
每個線程都有獨立的JNIEnv
- 初始化
//獲取class必須要在主線程中
jclass uuidutils_class_tmp = (*env)->FindClass(env,"com/dongnaoedu/androidlinux/UUIDUtils");
//創(chuàng)建全局引用
uuidutils_class_global = (*env)->NewGlobalRef(env,uuidutils_class_tmp);
//獲取jmethodId也可以在子線程中
uuidutils_get_mid = (*env)->GetStaticMethodID(env,uuidutils_class_global,"get","()Ljava/lang/String;");
- 創(chuàng)建多線程
void* th_fun(void* arg){
int i;
for (i = 0; i < 5; i++) {
JNIEnv* env;
//關(guān)聯(lián)參數(shù)
//JavaVMAttachArgs args = {JNI_VERSION_1_4, "my_thread", NULL};
//(*javaVM)->AttachCurrentThread(javaVM,&env,&args);
(*javaVM)->AttachCurrentThread(javaVM,&env,NULL);
jobject uuid_jstr = (*env)->CallStaticObjectMethod(env,uuidutils_class_global,uuidutils_get_mid);
const char* uuid_cstr = (*env)->GetStringUTFChars(env,uuid_jstr,NULL);
LOGI("uuid:%s",uuid_cstr);
//退出線程
if(i == 4){
goto end;
}
sleep(1);
}
end:
//取消關(guān)聯(lián)
(*javaVM)->DetachCurrentThread(javaVM);
pthread_exit((void*)0);
}
pthread_t tid;
pthread_create(&tid, NULL,th_fun,(void*)"NO1");
- 銷毀
(*env)->DeleteGlobalRef(env,uuidutils_class_global);