jvm - JNI,如何在 JNI 中访问当前的 Java 线程
问题描述
有没有办法从 JNI 获取 Java 线程(ID,名称)。我不是在谈论Thread.currentThread().getId()
从 java 到 JNI 的传递。JNI 是否提供 API 来访问当前正在运行的线程?
解决方案
您可以(如 Alex 所述)诉诸java.lang.Thread
.
// 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
推荐阅读
- visual-studio-code - Visual Studio Code - Exploration 和 Visual Studio Code 之间的主要区别是什么?
- solr - Solr - 强制方面显示当前不存在于任何文档中的枚举字段
- xamarin.forms - Xamarin 表单:相机和图库在 android 中不起作用,显示权限异常
- c - Valgrind 报告 libgc 错误
- angular - 测试无效表单时不显示角度错误文本
- python - catalan() 函数在这里如何工作?
- sql - SQL Query 查找一张表中行的差异
- php - 从 json 响应中设置在 HTML 中过滤的记录
- javascript - 为什么要安装前端库?
- android - 如何使用android通过语音命令(谷歌助手)在我的android应用程序中打开指定的活动