android关于native中Thread类的使用源码解析
作者:开发之奋斗人生
本文介绍了Android Native中Thread的使用,通过main.cpp启动线程,TestThread类依次调用onFirstRef、readyToRun和threadLoop方法,展示线程生命周期及执行流程,感兴趣的朋友跟随小编一起看看吧
简要概述
简单记录android中native关于thread的使用
源码位置:
system\core\libutils\include\utils\Thread.h system\core\libutils\Threads.cpp class Thread : virtual public RefBase Thread继承RefBase,有以下的一些特性 // Invoked after creation of initial strong pointer/reference. virtual void onFirstRef();
代码记录
main.cpp
#include <utils/Log.h>
#include <pthread.h>
#include "TestThread.h"
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "hello_test"
using namespace android;
int main(int args,char** argv) {
ALOGD("main start TestThread");
// TestThread
sp<TestThread> testThread = new TestThread;
testThread->run("TestThread", PRIORITY_URGENT_DISPLAY);
while(1){
if(!testThread->isRunning()){
break;
}
}
ALOGD("main end");
return 0;
}Android.bp
cc_binary{
name:"hello_test",
srcs:[
"main.cpp",
"TestThread.cpp",
],
shared_libs:[
"liblog",
"libutils",
],
cflags: [
"-Wno-error",
"-Wno-unused-parameter",
],
}TestThread.h
//
// Created by xxx on 25-6-8.
//
#ifndef ANDROID_TESTTHREAD_H
#define ANDROID_TESTTHREAD_H
#include <utils/threads.h>
#include <utils/Log.h>
namespace android {
class TestThread : public Thread {
public:
TestThread();
virtual void onFirstRef();
virtual status_t readyToRun();
virtual bool threadLoop();
virtual void requestExit();
private:
int cnt = 0;
};
}
#endif //ANDROID_TESTTHREAD_HTestThread.cpp
//
// Created by xxx on 25-6-8.
//
#include "TestThread.h"
namespace android{
TestThread::TestThread():Thread(false) {
ALOGD("TestThread");
}
void TestThread::onFirstRef(){
ALOGD("onFirstRef");
}
status_t TestThread::readyToRun(){
ALOGD("readyToRun");
return OK;
}
bool TestThread::threadLoop() {
cnt++;
ALOGD("threadLoop cnt = %d",cnt);
if(cnt >= 20){
return false;
}
return true;
}
void TestThread::requestExit(){
ALOGD("requestExit");
}
}日志打印如下所示
06-14 22:29:28.500 2094 2094 D hello_test: main start TestThread
06-14 22:29:28.500 2094 2094 D hello_test: TestThread
06-14 22:29:28.500 2094 2094 D hello_test: onFirstRef
06-14 22:29:28.501 2094 2096 D hello_test: readyToRun
06-14 22:29:28.502 2094 2096 D hello_test: threadLoop cnt = 1
...
06-14 22:29:28.505 2094 2096 D hello_test: threadLoop cnt = 20
06-14 22:29:28.505 2094 2094 D hello_test: main end
函数执行顺序 TestThread->onFirstRef->readyToRun->threadLoop
到此这篇关于android关于native中Thread类的使用的文章就介绍到这了,更多相关android native Thread类使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
