QThread 創建線程、關閉線程

代碼如題:

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
class MyThread : public QThread {
public:
    void stop() { //用於結束線程
        is_runnable =true;
        qDebug()<<"thread stop"<<QThread::currentThreadId();
    }
protected:
    void run() {
        while(true) {
            if(is_runnable) break;
            qDebug()<<"thread start:"<<QThread::currentThreadId();
        }
    }
private:
    bool is_runnable = false; //是否可以運行
};
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);
    qDebug()<<"Main:"<<QThread::currentThreadId();
    MyThread m;
    m.start();
    QThread::sleep(1);
    m.stop();
    m.quit();
    m.wait();
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章