背景
在Java調用Native函數時,爲了不阻塞主線程,在native代碼中另起線程處理耗時操作.
必要的庫
#include <pthread.h>
關鍵的函數
int pthread_create(pthread_t* thread,
pthread_attr_t const* attr,
void* (*start_routine)(void*),
void* args);
- 指向thread_t 類型變量的指針,函數用該指針返回新線程的句柄
- 指向pthread_attr_t 結構的指針形式存在的新線程屬性,可以通過該屬性指定新線程的棧基址,棧大小,守護大小,調度策略和調度優先級等,如果使用默認值,取值可能爲NULL.
- 第三個參數是指向線程啓動程序的函數指針,(類似Java中重寫Thread類中的run方法)啓動程序函數前面的格式
void* start_routine(void* args)
- 第四個參數是傳遞給上述start_routine(…)函數的參數指針,如果沒有參數,它可以爲NULL.
直接上Demo代碼
#include <jni.h>
#include <string.h>
#include <android/log.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#define LOG_TAG "pthread_learn"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
void* run(void * args)
{
LOGI("run() i'm running!");
clock_t * time = (clock_t *)args;
int i;
for (i = 0; i < 5; i++)
{
LOGI("Sleep leave %d second! callTime is %ld", (5 - i), *time);
//sleep one second;
sleep(1);
}
free(time);
}
jstring
Java_com_cm_jnitest_MainActivity_doInBackground(JNIEnv* env, jobject thiz)
{
int result;
pthread_t thread1;
clock_t* time = (clock_t *)malloc(sizeof(clock_t));
*time = clock();
LOGI("doInBackground() callTime is %ld", *time);
//Create Thread
result = pthread_create(&thread1, NULL, run, (void *)time);
if (result != 0)
LOGI("doInBackground() Create POSIX thread fail!");
else
LOGI("doInBackground() Create POSIX thread successfully!");
LOGI("doInBackground() finish!");
return (*env)->NewStringUTF(env, "doInBackground() finish!");
}
JNIEXPORT jint JNI_OnLoad(JavaVM* pVM, void* reserved)
{
LOGI("JNI_OnLoad() start!");
return JNI_VERSION_1_6;
}