您的位置:首页 > 编程语言 > Qt开发

Qt---多线程的简单实现

2016-07-01 21:06 393 查看
workthread中实现run()函数,编写线程运行时的操作

threaddlg中建立线程数组,通过start(),terminate(),wait()来控制各线程的开启、结束

workthread.h

#ifndef WORKTHREAD_H
#define WORKTHREAD_H

#include <QThread>

class WorkThread : public QThread
{
Q_OBJECT
public:
WorkThread();
protected:
void run();  //重新实现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;  //为了效果明显,每个数字打印8次
}
}


threaddlg.h

#ifndef THREADDLG_H
#define THREADDLG_H

#include <QDialog>
#include <QPushButton>
#include "workthread.h"
#define MAXSIZE 5

class ThreadDlg : public QDialog
{
Q_OBJECT

public:
ThreadDlg(QWidget *parent = 0);
~ThreadDlg();
private:
QPushButton *startBtn;
QPushButton *stopBtn;
QPushButton *quitBtn;
public slots:
void slotStart();
void slotStop();
private:
WorkThread *workThread[MAXSIZE];
};

#endif // THREADDLG_H


threaddlg.cpp

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

ThreadDlg::ThreadDlg(QWidget *parent)
: QDialog(parent)
{
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()
{

}

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

void ThreadDlg::slotStop()
{
for(int i=0;i<MAXSIZE;i++)
{
workThread[i]->terminate();  //强制结束线程
workThread[i]->wait();  //将一个线程挂起,直到超时或者该线程被唤醒。
}
startBtn->setEnabled(true);
stopBtn->setEnabled(false);
}


main.cpp

#include "threaddlg.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ThreadDlg w;
w.show();

return a.exec();
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: