Android native C++/c线程使用方式

###1.反射:

 class JavaThread extends Thread {

        private int count;

        public JavaThread(int count) {
            this.count = count;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i <= this.count; i++) {
                Log.e(TAG, "run: " + i);
            }
            stopThread();
        }
    }

    public void createThread(final int count) {
        javaThread = new JavaThread(count);
        javaThread.start();
    }

JNIEXPORT void JNICALL
Java_com_test_fuxi_1jni_JniUtils_userJavaThread(JNIEnv *env, jobject thiz, jint count) {

    LOGE("count=%d",count);

    jclass jclass1 = (*env)->FindClass(env, "com/test/fuxi_jni/JniUtils");
    jmethodID jmethodId = (*env)->GetMethodID(env, jclass1, "createThread", "(I)V");
    jobject object = (*env)->AllocObject(env, jclass1);
    (*env)->CallVoidMethod(env, object, jmethodId, count);

}

###2.使用C/C++ 利用pthread函数库

#include 

pthread_t pthread;//线程对象
JNIEnv *envPtr = nullptr;
jmethodID jmethodId;

jobject jobject1;

void *threadDoThings(int data) {

    int i = 0;
    for (; i < data; i++) {
        LOGE("jni thread do things=%d", i);
        //(I)V



    }
    pthread_exit(&pthread);
}

extern "C" JNIEXPORT void JNICALL
Java_com_test_fuxi_1jni_JniUtils_useCLangThread(JNIEnv *env, jobject thiz, jint count) {
    //
    envPtr = env;
    jclass jclass1 = envPtr->FindClass("com/test/fuxi_jni/MainActivity");
    jmethodId = envPtr->GetMethodID(jclass1, "cLangThreadResut", "(I)V");
    jobject1 = envPtr->AllocObject(jclass1);

    int result = pthread_create(&pthread, NULL, reinterpret_cast(threadDoThings),
                                reinterpret_cast(count));
    envPtr->CallVoidMethod(jobject1, jmethodId, count);
    if (result != JNI_OK) {
        jclass jclass1 = env->FindClass("java.lang.Exception");
        env->ThrowNew(jclass1, "create Thread fail from C++");
    }


}

你可能感兴趣的:(JNI学习)