28장. 네이티브 쓰레드 실행하기
$ vi StartThread.cpp#include <jni.h>
#include <iostream>
#include <thread>
void startThreads
(
JNIEnv *env,
jobject thiz,
jint count
)
{
//start thread1
std::thread th1 = std::thread([&] {
for(int i=1; i<=count; ++i) {
std::cout << "[thread1] counting : " << i << std::endl;
}
});
//start thread2
std::thread th2 = std::thread([&] {
for(int i=count; i>0; --i) {
std::cout << "[thread2] counting : " << i << std::endl;
}
});
//waiting for finish of the thread1
if(th1.joinable()) {
th1.join();
}
//waiting for finish of the thread2
if(th2.joinable()) {
th2.join();
}
}
JNIEXPORT jint JNICALL JNI_OnLoad
(
JavaVM *vm,
void *reserved
)
{
JNIEnv *env;
if(vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6)) {
return -1;
}
JNINativeMethod nm[1] = {
{
const_cast<char*>("startThreads"),
const_cast<char*>("(I)V"),
reinterpret_cast<void*>(startThreads)
}
};
jclass cls = env->FindClass("Client");
env->RegisterNatives(cls, nm, 1);
return JNI_VERSION_1_6;
}Last updated