1. Android C++多線程
1.1 Android C++ 線程簡介
我們都知道Android是基于Linux內(nèi)核的,而Linux是遵循POSIX線程標(biāo)準(zhǔn)的,POSIX線程庫中有一系列Pthreads API方便我們對(duì)Linux線程的操作。所以我們在Android中使用C/C++線程也就轉(zhuǎn)到了使用POSIX線程庫。他們都在頭文件 “pthread.h” 中。
1.2 創(chuàng)建子線程
1.2.1 基礎(chǔ)概念
使用 C++ 創(chuàng)建子線程需要先了解一些基本的概念。
- pthread_t
用于聲明一個(gè)線程對(duì)象,例如 p_thread thread
//導(dǎo)入頭文件
#include "pthread.h"
//聲明一個(gè)線程
pthread_t pthread;
- pthread_creat
用于創(chuàng)建一個(gè)實(shí)際的線程如:pthread_create(&pthread,NULL,threadCallBack,NULL);總共接收4個(gè)參數(shù),第一個(gè)參數(shù)為pthread_t對(duì)象,第二個(gè)參數(shù)為線程的一些屬性我們一般傳
NULL就行,第三個(gè)參數(shù)為線程執(zhí)行的函數(shù)(void* threadCallBack(void data)),第四個(gè)參數(shù)是傳遞給線程的參數(shù)是void類型的既,可以傳任意類型。
extern "C"
JNIEXPORT void JNICALL
Java_com_liaowj_jni_thread_JniThreadDemo_createThread(JNIEnv *env, jobject instance) {
//創(chuàng)建 thread 對(duì)象
pthread_create(&pthread, NULL, threadCallback, NULL);
}
- pthread_exit
用于退出線程如:pthread_exit(&thread),參數(shù)也可以傳NULL。注:線程回調(diào)函數(shù)最后必須調(diào)用此方法,不然APP會(huì)退出(掛掉)。
//定義一個(gè)線程的回調(diào)
void *threadCallback(void *data) {
LOGI("Hello From C++ Thread")
//執(zhí)行線程完畢之后,退出線程
pthread_exit(&pthread);
1.2.2 完整代碼
native-thread-lib.cpp完整代碼,執(zhí)行調(diào)用 createThread 方法,會(huì)創(chuàng)建線程,并且執(zhí)行線程,在控制臺(tái)中輸出 Hello From C++ Thread。
#include <jni.h>
#include <string>
#include "android/log.h"
#define LOGI(FORMAT, ...) __android_log_print(ANDROID_LOG_INFO,"liaowejian",FORMAT,##__VA_ARGS__);
#include "pthread.h"
//聲明一個(gè)線程
pthread_t pthread;
//定義一個(gè)線程的回調(diào)
void *threadCallback(void *data) {
LOGI("Hello From C++ Thread")
//執(zhí)行線程完畢之后,退出線程
pthread_exit(&pthread);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_liaowj_jni_thread_JniThreadDemo_createThread(JNIEnv *env, jobject instance) {
//創(chuàng)建 thread 對(duì)象
pthread_create(&pthread, NULL, threadCallback, NULL);
}
JniThreadDemo.java
public class JniThreadDemo {
static {
System.loadLibrary("native-thread-lib");
}
public native void createThread();
}
/**
* @author liaowj
* @time 2019/1/1 12:38 AM
* @desc
**/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createThread(View view) {
JniThreadDemo jniThreadDemo = new JniThreadDemo();
jniThreadDemo.createThread();
}
}

項(xiàng)目源碼:
https://github.com/liaowjcoder/Jni4Android
記錄于 2018年11月9號(hào)