背景
在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;
}