首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JNI,如何在JNI中访问当前Java线程

JNI,如何在JNI中访问当前Java线程
EN

Stack Overflow用户
提问于 2019-05-06 09:30:14
回答 1查看 958关注 0票数 1

有没有办法从JNI获取Java线程(ID,名称)。我不是在谈论将Thread.currentThread().getId()从java传递给JNI。JNI是否提供API来访问当前正在运行的线程?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-07 02:11:27

你可以(正如亚历克斯提到的那样)求助于java.lang.Thread

代码语言:javascript
复制
// First, we have to find Thread class
jclass cls = (*env)->FindClass(env, "java/lang/Thread");

// Then, we can look for it's static method 'currentThread'
/* Remember that you can always get method signature using javap tool
     > javap -s -p java.lang.Thread | grep -A 1 currentThread
         public static native java.lang.Thread currentThread();
           descriptor: ()Ljava/lang/Thread;
*/
jmethodID mid =
  (*env)->GetStaticMethodID(env, cls, "currentThread", "()Ljava/lang/Thread;");

// Once you have method, you can call it. Remember that result is
// a jobject
jobject thread = (*env)->CallStaticObjectMethod(env, cls, mid);
if( thread == NULL ) {
  printf("Error while calling static method: currentThread\n");
}

// Now, we have to find another method - 'getId'
/* Remember that you can always get method signature using javap tool
     > javap -s -p java.lang.Thread | grep -A 1 getId
         public long getId();
           descriptor: ()Jjavap -s -p java.lang.Thread | grep -A 1 currentThread
*/
jmethodID mid_getid =
  (*env)->GetMethodID(env, cls, "getId", "()J");
if( mid_getid == NULL ) {
  printf("Error while calling GetMethodID for: getId\n");
}

// This time, we are calling instance method, note the difference
// in Call... method
jlong tid = (*env)->CallLongMethod(env, thread, mid_getid);

// Finally, let's call 'getName' of Thread object
/* Remember that you can always get method signature using javap tool
     > javap -s -p java.lang.Thread | grep -A 1 getName
         public final java.lang.String getName();
           descriptor: ()Ljava/lang/String;
*/
jmethodID mid_getname =
  (*env)->GetMethodID(env, cls, "getName", "()Ljava/lang/String;");

if( mid_getname == NULL ) {
  printf("Error while calling GetMethodID for: getName\n");
}

// As above, we are calling instance method
jobject tname = (*env)->CallObjectMethod(env, thread, mid_getname);

// Remember to retrieve characters from String object
const char *c_str;
c_str = (*env)->GetStringUTFChars(env, tname, NULL);
if(c_str == NULL) {
  return;
}

// display message from JNI
printf("[C   ] name: %s id: %ld\n", c_str, tid);

// and make sure to release allocated memory before leaving JNI
(*env)->ReleaseStringUTFChars(env, tname, c_str);

你可以在这里找到完整的样本:https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo044

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55997811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档