Qt开发——QThread多线程初探

南楼画角 提交于 2020-01-28 14:54:51

目录

效果:

threaddlg.h

threaddlg.cpp

workthread.h

workthread.cpp


效果:

开启多线程后,使用qDebug()打印观察输出;

停止多线程时,系统不会立即终止这个线程,线程何时终止取决于操作系统的调度,使用wait()等待线程阻塞直到超时退出

threaddlg.h

#ifndef THREADDLG_H
#define THREADDLG_H

#include <QDialog>
#include <QThread>
#include <QPushButton>
#include <QHBoxLayout>
#include "workthread.h"

static const int MAXSIZE = 1;//定义线程数量

class ThreadDlg : public QDialog
{
    Q_OBJECT

public:
    ThreadDlg(QWidget *parent = nullptr);
    ~ThreadDlg();

public slots:
    void slotStart();//开启线程
    void slotStop();//结束线程

private:
    QPushButton *startBtn;
    QPushButton *stopBtn;
    QPushButton *quitBtn;
    QHBoxLayout *mainLayout;

    WorkThread *workThread[MAXSIZE];//记录所启动的线程
};

#endif // THREADDLG_H

threaddlg.cpp

#include "threaddlg.h"

ThreadDlg::ThreadDlg(QWidget *parent)
    : QDialog(parent)
{
    setWindowIcon(QIcon("icon.png"));
    setWindowTitle(QStringLiteral("多线程实例"));
    //布局设计
    startBtn = new QPushButton(QStringLiteral("开始"));
    stopBtn = new QPushButton(QStringLiteral("停止"));
    quitBtn = new QPushButton(QStringLiteral("退出"));
    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()
{

}

void ThreadDlg::slotStop(){
    for(int i=0;i<MAXSIZE;i++){
        workThread[i]->terminate();//退出线程
        workThread[i]->wait();//等待线程阻塞直到超时退出
    }
    startBtn->setEnabled(true);
    stopBtn->setEnabled(false);
}

void ThreadDlg::slotStart(){
    for(int i=0;i<MAXSIZE;i++){
        workThread[i]=new WorkThread();//创建线程并保存指针
    }
    for(int i=0;i<MAXSIZE;i++){
        workThread[i]->start();//线程开始运行
    }
    startBtn->setEnabled(false);
    stopBtn->setEnabled(true);
}

workthread.h

#ifndef WORKTHREAD_H
#define WORKTHREAD_H

#include <QThread>
#include <QDebug>

class WorkThread : public QThread
{
    Q_OBJECT

public:
    WorkThread();

protected:
    void run();

};

#endif // WORKTHREAD_H

workthread.cpp

#include "workthread.h"

WorkThread::WorkThread()
{

}

//线程运行内容
void WorkThread::run(){
    while(true){
        for(int i=0;i<10;i++){
            qDebug()<<i<<" "<<i<<" "<<i<<" "<<i<<" "<<i<<" "<<endl;
        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!