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();
}
以上代碼是實現了最簡單的多線程的操作,運行結果如下:
輸出結果中,帶紅框的是是value =10的情況時的線程,不帶紅框的是value =20 輸出的結果。