MyThread.java
public class MyThread { static { // 加载全路径名 System.load("/root/lib/libMyThreadNative.so"); // 加载环境变量 // System.loadLibrary("libMyThreadNative"); } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } public void start() { start0(); } // javah MyThread private native void start0();}
MyThread.h
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class org_example_se_concurrency_thread_MyThread */#ifndef _Included_org_example_se_concurrency_thread_MyThread#define _Included_org_example_se_concurrency_thread_MyThread#ifdef __cplusplusextern "C" {#endif/* * Class: org_example_se_concurrency_thread_MyThread * Method: start0 * Signature: ()V */JNIEXPORT void JNICALL Java_MyThread_start0 (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif
MyThread.c
#include <stdio.h>#include <unistd.h>#include <pthread.h>#include <MyThread.h>using namespace std;pthread_t pid; // 定义变量,接收创建后的线程 IDvoid *java_start(void *args) { while (1) { usleep(1000 * 1000); // 单位是微秒 printf("this is java_start method\n"); }}JNIEXPORT void JNICALL Java_MyThread_start0(JNIEnv *env, jobject obj) { pthread_create(&pid, NULL, java_start, NULL); while (1) { usleep(1000 * 1000); // 单位是微秒 printf("this is start0 method\n"); }}// gcc my_thread.cpp -o my_thread.out -pthread// ./my_thread.outint main() { pthread_create(&pid, NULL, java_start, NULL); while (1) { usleep(1000 * 1000); // 单位是微秒 printf("this is start0 method\n"); } return 0;}
GCC 编译
gcc -fPIC -I /usr/local/jdk1.8.0_261/include -I /usr/local/jdk1.8.0_261/include/linux -shared -o libMyThreadNative.so my_thread.cpp -pthread
调用
java MyThread