android jni 多线程编程 join thread

14 篇文章 5 订阅

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---");
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值