package com.tigger; public class MyThread { static { //装载库,保证jvm在启动的时候就会装载 System.loadLibrary( "TiggerThreadNative" ); } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.s
package com.tigger; public class MyThread { static {
//装载库,保证jvm在启动的时候就会装载 System.loadLibrary("TiggerThreadNative"); } public static void main(String[] args) { MyThread myThread=new MyThread(); myThread.start0(); } private native void start0(); }
1、编写java代码 MyThread.java 使用jni调用一个c程序,上传至/home/mythread/com/tigger/目录下
2、编译成class程序 javac MyThread.java
3、生成头文件 javah packageName.ClassName 此命令需要在包外执行,javac命令需要在包当中执行
javah com.tigger.MyThread
4、将编译好的头文件移动到MyThread.java同级目录下
5、开始编写c程序threadNew.c,并放到/home/mythread/com/tigger/ 目录下
#include <pthread.h> #include <stdio.h> #include "com_tigger_MyThread.h" //需导入刚刚编译的.h文件 pthread_t pid; void* thread_entity(void* arg) { while(1){ usleep(100); printf("I am new Thread\n"); } } //此方法名需要从刚刚编译的.h头文件里复制方法名,这里参数写死 JNIEXPORT void JNICALL Java_com_tigger_MyThread_start0 (JNIEnv * evn, jobject c1) { pthread_create(&pid,NULL,thread_entity,NULL); while(1){ usleep(100); printf("I am main\n"); } } int main(){ return 0; }
6、将threadNew.c编译成一个动态链接库,这样在java 代码里会被load到内存
gcc -I /usr/java/jdk1.8.0_221/include -I /usr/java/jdk1.8.0_221/include/linux threadNew.c -fPIC -shared -o libTiggerThreadNative.so -pthread
7、将编译好的.so文件移动到/home/mythread/目录下 ,并加入到path,这样jvm才能load到
mv libTiggerThreadNative.so /home/mythread/
进入mythread目录执行命令
export LD_LIBRARY_PATH=/home/mythread/
8、测试
java com.tigger.MyThread