1.Android 把线程C++封装Thread类,它是线程的基类
2.使用Thread时,创建一个类继承于Thread类,实现threadLoop()方法是纯虚函数,在子类中实现
3.启动线程,调用run()函数,并执行threadLoop()虚函数
接口说明:
// 启动线程,但是需要在派生类中实现threadLoop()
// NOLINTNEXTLINE(google-default-arguments)
virtual status_t run( const char* name,
int32_t priority = PRIORITY_DEFAULT,
size_t stack = 0);
// 启动线程退出,这是一个异步接口,函数会立刻返回,但是线程不会立刻退出
virtual void requestExit();
// 派生类可以重载此函数,进行线程初始化
virtual status_t readyToRun();
//先调用 requestExit() 请求退出线程,然后接着等待退出,不立即返回
status_t requestExitAndWait();
// 等待线程退出
status_t join();
测试代码:
ThreadTest.h
#ifndef THREAD_TEST_H
#define THREAD_TEST_H
#include <utils/Thread.h>
#include <stdio.h>
#include <stdlib.h>
namespace android {
class ThreadTest: public Thread {
public:
explicit Animation();
private:
int mIndex;
virtual bool threadLoop();
};
}
#endif
ThreadTest.cpp
#include "thread_test.h"
namespace android {
ThreadTest::ThreadTest() :
Thread(false)
{
printf("ThreadTest::ThreadTest()\n");
mIndex = 0;
}
bool ThreadTest::threadLoop()
{
printf("ThreadTest::threadLoop()\n");
while (mIndex < 10)
{
sleep(1);
mIndex++;
}
return 0;
}
}
main.cpp
int main()
{
sp < ProcessState > proc(ProcessState::self());
ProcessState::self()->startThreadPool();
sp < ThreadTest> test = new ThreadTest();
test ->run("ThreadTest");
printf("main()\n");
test ->join();
IPCThreadState::self()->joinThreadPool();
return 0;
}