Qt多线程简单实现Widget

threaddlg.h
#ifndef THREADDLG_H
#define THREADDLG_H
#define MAXSIZE 1   //定义线程数目
#include <QDialog>
#include <QPushButton>
#include "workthread.h"

QT_BEGIN_NAMESPACE
namespace Ui { class threaddlg; }
QT_END_NAMESPACE

class threaddlg : public QDialog
{
    Q_OBJECT

public:
    threaddlg(QWidget *parent = nullptr);
    ~threaddlg();
public slots:
    void slotStart();   //启动线程
    void slotStop();    //终止线程
private:
    Ui::threaddlg *ui;

private:
    QPushButton *startBtn;
    QPushButton *stopBtn;
    QPushButton *quitBtn;
private:
    workthread *workThread[MAXSIZE];    //指向工作线程的私有指针数组,记录所启动的全部线程


};
#endif // THREADDLG_H

threaddlg.cpp
#include "threaddlg.h"
#include "ui_threaddlg.h"
#include <QHBoxLayout>

/**
 * 单击"开始"启动  MAXSIZE  个线程  循环打印  0-9
 * 单一线程输出结果顺序打印
 * 多线程输出结果乱序打印
 */

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()));
}

threaddlg::~threaddlg()
{
    delete ui;
}

/**
 * @brief threaddlg::slotStart
 * 使用两个循环
 * 为了新建的线程尽可能同时执行
 */
void threaddlg::slotStart()
{     
    for (int i=0;i<MAXSIZE;i++) {
        //创建指定数目的线程并保存到指针数组中
        workThread[i] = new workthread();
    }
    for (int i=0;i<MAXSIZE;i++) {
        //调用QThread基类的start()函数
        //次函数将启动函数run(),从而使得线程开始真正运行
        workThread[i]->start();
    }
    startBtn->setEnabled(false);
    stopBtn->setEnabled(true);
}

void threaddlg::slotStop()
{
    for (int i =0;i<MAXSIZE;i++) {
        //调用QThread基类的terminate(),函数
        //依次终止保存在数组中的类实例
        //并不会立刻终止这个线程
        //该线程何时终止取决于操作系统的调度策略
        workThread[i]->terminate();
        //使得线程阻塞等待直到退出或超时
        workThread[i]->wait();
    }
    startBtn->setEnabled(true);
    stopBtn->setEnabled(false);
}
}
workthread.h
#ifndef WORKTHREAD_H
#define WORKTHREAD_H

#include <QThread>
class workthread : public QThread
{
    Q_OBJECT
public:
    workthread();

protected:
    void run();

};

#endif // WORKTHREAD_H

workthread.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<<n<<n;
        }
    }
}
main.cpp
#include "threaddlg.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    threaddlg w;
    w.show();
    return a.exec();
}


版权声明:本文为qq_48167493原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。