QT5 多執行緒簡單實現
阿新 • • 發佈:2019-01-06
檔案中載入介面顯示的控制元件,變數都放在了threaddlg.h檔案中.
threaddld.h原始碼如下:
原始檔threaddlg.cpp中定義了變數的作用,還有方法的實現,threaddlg.cpp原始碼如下:#ifndef THREADDLG_H #define THREADDLG_H #include <QDialog> #include <QPushButton> #include "workthread.h" #define MAXSIZE 2 namespace Ui { class ThreadDlg; } class ThreadDlg : public QDialog { Q_OBJECT public: explicit ThreadDlg(QWidget *parent = 0); ~ThreadDlg(); private: Ui::ThreadDlg *ui; QPushButton *startBtn; QPushButton *stopBtn; QPushButton *quitBtn; WorkThread *workThraed[MAXSIZE]; public slots: void slotStart(); void slotStop(); }; #endif // THREADDLG_H
介面顯示的類已經完成了,接下來再建立一個類,這個類的作用是實現多執行緒的用法:#include "threaddlg.h" #include "ui_threaddlg.h" #include <QHBoxLayout> #include <QDebug> ThreadDlg::ThreadDlg(QWidget *parent) : QDialog(parent), ui(new Ui::ThreadDlg) { ui->setupUi(this); setWindowTitle(tr("執行緒")); startBtn=new QPushButton(tr("開始")); stopBtn=new QPushButton(tr("停止")); quitBtn=new QPushButton(tr("退出")); QHBoxLayout *mainLayout=new QHBoxLayout(this); mainLayout->addWidget(startBtn); mainLayout->addWidget(stopBtn); mainLayout->addWidget(quitBtn); connect(startBtn,SIGNAL(clicked()),this,SLOT(slotStart())); connect(stopBtn,SIGNAL(clicked()),this,SLOT(slotStop())); connect(quitBtn,SIGNAL(clicked()),this,SLOT(close())); } void ThreadDlg::slotStart() { for(int i=0;i<MAXSIZE;i++) { workThraed[i]=new WorkThread(); } for(int i=0;i<MAXSIZE;i++) { workThraed[i]->start(); } startBtn->setEnabled(false); stopBtn->setEnabled(true); } void ThreadDlg::slotStop() { for(int i=0;i<MAXSIZE;i++) { workThraed[i]->terminate(); workThraed[i]->wait(); } startBtn->setEnabled(true); stopBtn->setEnabled(false); } ThreadDlg::~ThreadDlg() { delete ui; }
還是一樣先建立一個頭檔案用來放多執行緒任務中需要的變數和方法的,標頭檔案workthread.h的原始碼如下:
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include <QThread>
class WorkThread : public QThread
{
Q_OBJECT
public:
WorkThread();
protected:
void run();
};
#endif // WORKTHREAD_H
想知道public和protected區別的話可以百度下
方法定義好了之後,在cpp檔案中實現方法。workthred.CPP檔案的原始碼如下:
#include "workthread.h"
#include <QtDebug>
WorkThread::WorkThread()
{
}
void WorkThread::run()
{
while(true)
{
for(int n=0;n<10;n++)
qDebug()<<n<<n<<n<<n<<n<<n;
}
}
#include <> 相當於java中的 import (導包),在類中引用其他類中的變數,就要導包。