android关于native中Thread类的使用
文章目录
- 简要概述
- 代码记录
简要概述
简单记录android中native关于thread的使用
源码位置:
system\core\libutils\include\utils\Thread.h
system\core\libutils\Threads.cppclass 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");// TestThreadsp<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_H
TestThread.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