android jni 多线程编程 join thread:
//
// Created by 11 on 2019/3/7.
//
#include <com_reactnative_jason_jnidome_JNIClass.h>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <android/log.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <cstdlib>
#include <fcntl.h>
#include <cerrno>
#include <stdarg.h>
#include <cstdlib>
#include <limits.h>
#include <strings.h>
#include <string.h>
#include <float.h>
#include <cmath>
#include <error.h>
#include <cstdlib>
#include <csignal>
#include <unistd.h>
#include <pthread.h>
using namespace std;
class One{
public:
void func();
};
extern "C" {
jstring Java_com_reactnative_jason_jnidome_JNIClass_getStringForJNI(JNIEnv *env, jobject jobject1, jstring jstring1) {
const char *outs = env->GetStringUTFChars(jstring1, JNI_FALSE);
One one;
one.func();
return env->NewStringUTF(outs);
}
}
#define NUM_THREADS 5
struct Augments{
int arg;
};
void outString(const char *ins){
LOGI("jason:%s", ins);
}
void outInt(int a){
LOGI("jason:%d", a);
}
void outFloat(float a){
LOGI("jason:%f", a);
}
void *PrintHello(void *threadid)
{
Augments *augments = (Augments *)(threadid);
sleep((unsigned int)(augments->arg+1));
outInt(augments->arg);
pthread_exit(NULL);
}
void One::func() {
pthread_t pThread[NUM_THREADS];
Augments augments[NUM_THREADS];
pthread_attr_t attr;
void *status;
//创建可连接线程
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (int i = 0; i < NUM_THREADS; ++i) {
outString("create thread id:");
outInt(i);
augments[i].arg=i;
int ret = pthread_create(&pThread[i], NULL, PrintHello, (void*)&(augments[i]));
if (ret!=0){
outString("create thread error:");
outInt(i);
}
}
pthread_attr_destroy(&attr);
outString("create end");
//等待每个线程执行完毕
for (int i = 0; i < NUM_THREADS; ++i) {
int ret=pthread_join(pThread[i], &status);
if (ret){
outString("wait join error:");
outString((const char *)(status));
outInt(i);
}
}
outString("end---");
}