最后,我发现JNI方法是解决我的问题的最佳方法。作为参考,我发布了代码并为其构建了说明(基于Wikipedia
的示例):
负责连接C代码的Java类(
GetThreadID.java):
public class GetThreadID { public static native int get_tid(); static { System.loadLibrary("GetThreadID"); }}负责获取线程ID(
GetThread.c)的C文件:
#include <jni.h>#include <syscall.h>#include "GetThreadID.h"JNIEXPORT jint JNICALLJava_GetThreadID_get_1tid(JNIEnv *env, jobject obj) { jint tid = syscall(__NR_gettid); return tid;}有关如何使用
GetThreadID类的示例:
class Main { public static void main(String[] args) { int tid = GetThreadID.get_tid(); System.out.println("TID=" + tid); }}最后,构建说明(
javah自动生成
GetThreadID.h):
JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:bin/javac::")export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.javac GetThreadID.javajavah GetThreadIDgcc -I${JAVA_HOME}/include -fPIC -shared GetThreadID.c -o libGetThreadID.sojavac Main.javajava Main


