- 写一个线程类,继承QThread
//workthread.h
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include <QThread>
class WorkThread : public QThread
{
Q_OBJECT
public:
WorkThread();
protected:
//重写run函数,业务逻辑写在该函数中
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;
}
}
2、编写一个自定义Dialog
//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);
}
注意:“在QThread中定义的所有东西都属于创建该QThread的线程。”,QT中继承Qthread类后,在类中定义的对象或或对象的指针都是属于主线程的。次线程正真意义上的实体内容实在实现run()函数里。所以,要将mythread线程里的对象或指针创建,需要在run()函数里,创建或分配对象空间。