Android线程封装基类Thread

Android对Linux线程提供了C++封装Thread类,它是线程的基类。使用Thread类,需创建一个新类继承于Thread类,并实现threadLoop()方法,它即是线程函数。要启动线程,调用run()函数即可。
 
 /*
 * Android线程封装的基类
 */
class Thread : virtual public RefBase
{
public:
                        Thread(bool canCallJava = true);
                        virtual             ~Thread();

                        /* 启动线程,即创建一个新的线程并执行threadLoop()虚函数 */
                         virtual status_t    run(    const char* name = 0,
                                int32_t priority = PRIORITY_DEFAULT,
                                size_t stack = 0);
    
                         /* 要求退出线程(这个函数是异步的) */
                        virtual void        requestExit();

                        /* 可以重载此虚函数以进行初始化工作,但必须显示调用 */
                        virtual status_t    readyToRun();
    
                        /* 要求线程退出(同步的) */
                        status_t    requestExitAndWait();

protected:
                        /* 判断requestExit()是否被调用过 */
                        bool        exitPending() const;
    
private:
                        /* 线程函数。若此函数返回true,当requestExit()没被调用过时会在次调用此函数;若返回false,
                        * 在该函数返回时线程将退出
                        */
                        virtual bool        threadLoop() = 0;

private:
                        Thread& operator=(const Thread&);
                        static  int             _threadLoop(void* user);
                        const   bool            mCanCallJava;
                        thread_id_t     mThread;
                        Mutex           mLock;
                        Condition       mThreadExitedCondition;
                        status_t        mStatus;
                        volatile bool           mExitPending;
                         volatile bool           mRunning;
                        sp<Thread>      mHoldSelf;
#if HAVE_ANDROID_OS
                        int             mTid;
#endif
};

转载请保留:http://hi.baidu.com/%B6%C5%B2%FD%B1%F2/


你可能感兴趣的:(thread,android,linux,user,OS,化工)