代码部分:
threaddig.h
#ifndef THREADDIG_H
#define THREADDIG_H
#include <QDialog>
#include "workthread.h"
#define MAXSIZE 5 //MAXSIZE宏定义了线程的数目
namespace Ui {
class ThreadDig;
}
class ThreadDig : public QDialog
{
Q_OBJECT
public:
explicit ThreadDig(QWidget *parent = 0);
~ThreadDig();
public slots:
void slotStart();//启动线程
void slotStop();//停止线程
private:
Ui::ThreadDig *ui;
WorkThread* workThread[MAXSIZE];//指向工作线程(WorkThread)的私有指针数组workThread,记录所有启动的全部线程
};
#endif // THREADDIG_H
threaddig.cpp
#include "threaddig.h"
#include "ui_threaddig.h"
ThreadDig::ThreadDig(QWidget *parent) :
QDialog(parent),
ui(new Ui::ThreadDig)
{
ui->setupUi(this);
connect(ui->startBtn,SIGNAL(clicked()),this,SLOT(slotStart()));
connect(ui->stopBtn,SIGNAL(clicked()),this,SLOT(slotStop()));
connect(ui->quitBtn,SIGNAL(clicked()),this,SLOT(close()));
}
void ThreadDig::slotStart()
{
for(int i=0;i<MAXSIZE;i++)
{
workThread[i] = new WorkThread();
}
for(int i=0;i<MAXSIZE;i++)
{
workThread[i]->start();//用于启动run()函数。从而使线程开始运行
}
ui->startBtn->setEnabled(false);
ui->stopBtn->setEnabled(true);
}
void ThreadDig::slotStop()
{
for(int i=0;i<MAXSIZE;i++)
{
workThread[i]->terminate();
workThread[i]->wait();
}
ui->startBtn->setEnabled(true);
ui->stopBtn->setEnabled(false);
}
ThreadDig::~ThreadDig()
{
delete ui;
}
workthread.h
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include <QThread>
class WorkThread : public QThread
{
Q_OBJECT
public:
explicit WorkThread();
protected:
void run();
signals:
public slots:
};
#endif // WORKTHREAD_H
workthread.cpp
#include "workthread.h"
#include <QDebug>
WorkThread::WorkThread()
{
}
void WorkThread::run()
{
while(true)
{
for(int n=0;n<10;n++)
{
qDebug()<<n<<n<<n<<n<<n<<n;
}
}
}
仅供个人学习记录