Qt的多線程總結以及使用(一)


Qt提供QThread類以進行多任務的處理。Qt提供的線程可以做到單個進程做不到的事情。在這里實現最簡單的一個多線程。最簡單的線程的基類為QThread,然后需要重寫QThread的run(),在run()函數中實現的功能就是在線程中實現的功能。代碼如下:

YLThread.h

#ifndef YLTHREAD_H
#define YLTHREAD_H
#include <QThread>

class YLThread : public QThread
{
 Q_OBJECT
public:
 YLThread();

protected:
 void run();
public:
 //用來打印數據
 void setValue(int num);
private:
 int printNum;
};

#endif // YLTHREAD_H

YLThread.cpp

#include "YLThread.h"
#include <QDebug>
YLThread::YLThread()
{

}

void YLThread::run(){

 //打印數據
 for(int i =0;i < 5;i++){
 p, li { white-space: pre-wrap; }

qDebug()<<QStringLiteral("value=%1輸出:-----").arg(printNum)<<i+printNum;
 }
}
void YLThread::setValue(int num)
{
 printNum = num;
}

main.cpp

#include <QCoreApplication>
#include <QDebug>
#include "YLThread.h"
int main(int argc, char *argv[])
{
 QCoreApplication a(argc, argv);

 YLThread* thread01 = new YLThread() ;
 thread01->setValue(10);

 YLThread* thread02 = new YLThread() ;
 thread02->setValue(20);

 thread01->start();
 thread02->start();

 return a.exec();
}

以上代碼是實現了最簡單的多線程的操作,運行結果如下:

636D13F7-604B-4F6D-A53A-DC53C3557042.png
輸出結果中,帶紅框的是是value =10的情況時的線程,不帶紅框的是value =20 輸出的結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM