MyThread.java

  1. public class MyThread {
  2. static {
  3. // 加载全路径名
  4. System.load("/root/lib/libMyThreadNative.so");
  5. // 加载环境变量
  6. // System.loadLibrary("libMyThreadNative");
  7. }
  8. public static void main(String[] args) {
  9. MyThread myThread = new MyThread();
  10. myThread.start();
  11. }
  12. public void start() {
  13. start0();
  14. }
  15. // javah MyThread
  16. private native void start0();
  17. }

MyThread.h

  1. /* DO NOT EDIT THIS FILE - it is machine generated */
  2. #include <jni.h>
  3. /* Header for class org_example_se_concurrency_thread_MyThread */
  4. #ifndef _Included_org_example_se_concurrency_thread_MyThread
  5. #define _Included_org_example_se_concurrency_thread_MyThread
  6. #ifdef __cplusplus
  7. extern "C" {
  8. #endif
  9. /*
  10. * Class: org_example_se_concurrency_thread_MyThread
  11. * Method: start0
  12. * Signature: ()V
  13. */
  14. JNIEXPORT void JNICALL Java_MyThread_start0
  15. (JNIEnv *, jobject);
  16. #ifdef __cplusplus
  17. }
  18. #endif
  19. #endif

MyThread.c

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <pthread.h>
  4. #include <MyThread.h>
  5. using namespace std;
  6. pthread_t pid; // 定义变量,接收创建后的线程 ID
  7. void *java_start(void *args) {
  8. while (1) {
  9. usleep(1000 * 1000); // 单位是微秒
  10. printf("this is java_start method\n");
  11. }
  12. }
  13. JNIEXPORT void JNICALL Java_MyThread_start0(JNIEnv *env, jobject obj) {
  14. pthread_create(&pid, NULL, java_start, NULL);
  15. while (1) {
  16. usleep(1000 * 1000); // 单位是微秒
  17. printf("this is start0 method\n");
  18. }
  19. }
  20. // gcc my_thread.cpp -o my_thread.out -pthread
  21. // ./my_thread.out
  22. int main() {
  23. pthread_create(&pid, NULL, java_start, NULL);
  24. while (1) {
  25. usleep(1000 * 1000); // 单位是微秒
  26. printf("this is start0 method\n");
  27. }
  28. return 0;
  29. }

GCC 编译

  1. 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

调用

  1. java MyThread