如何防止我的 JNI C 代码在它启动的 JVM 仍在运行 Java 线程时退出?

问题描述 投票:0回答:0

我正在编写一个 C++ 应用程序,它将依赖另一个 embedded Java 应用程序。为了简单起见,我们假设 Java 应用程序是以下类:

package com.test;

public class CallbackFromJava {

    private final int periodInMillis;
    private final Thread thread;
    private boolean volatile isRunning = true;

    public CallbackFromJava(int periodInMillis) {
        this.periodInMillis = periodInMillis;
        this.thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while(isRunning) {
                        Thread.sleep(periodInMillis);
                        hiFromJava(System.currentTimeMillis());
                    }
                } catch(InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    public void start() {
        thread.start();
    }

    public void end() {
        isRunning = false;
    }

    public native void hiFromJava(long l);

}

我的 C++ 应用程序的准系统如下。我的问题是 当 JVM 正在运行上面的线程时,如何防止它退出?

#include <jni.h>

int main()
{
       Using namespace std;
       JavaVM *jvm;                      // Pointer to the JVM (Java Virtual Machine)
       JNIEnv *env;                      // Pointer to native interface
           //================== prepare loading of Java VM ============================
       JavaVMInitArgs vm_args;                        // Initialization arguments
       JavaVMOption* options = new JavaVMOption[1];   // JVM invocation options
       options[0].optionString = "-Djava.class.path=.";   // where to find java .class
       vm_args.version = JNI_VERSION_1_6;             // minimum Java version
       vm_args.nOptions = 1;                          // number of options
       vm_args.options = options;
       vm_args.ignoreUnrecognized = false;     // invalid options make the JVM init fail
           //=============== load and initialize Java VM and JNI interface =============
       jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);  // YES !!
       delete options;    // we then no longer need the initialisation options. 
       if (rc != JNI_OK) {
              // TO DO: error processing... 
             cin.get();
             exit(EXIT_FAILURE);
       }
          //=============== Display JVM version =======================================
       cout << "JVM load succeeded!\n";

        // HERE I'LL CALL A STATIC METHOD ON A JAVA CLASS THAT WILL START A JAVA THREAD
        // What do I do here to keep my C application running while the JVM has my thread running?

       jvm->DestroyJavaVM();
}
java c++ c java-native-interface
© www.soinside.com 2019 - 2024. All rights reserved.