threads.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TEMPLATE = app
CONFIG += console thread
HEADERS = thread.h \
threaddialog.h
SOURCES = main.cpp \
thread.cpp \
threaddialog.cpp
OTHER_FILES +=
thread.h 线程的定义,线程中最主要的函数是run()和stop()函数,run()函数是线程启动之后要执行的函数,而线程的终止要用stop()函数
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QPushButton>
#include <QLayout>
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
void setMessage(const QString &message);
void stop();
protected:
void run();
private:
QString messageStr;
volatile bool stopped; //函数终止的标志位 必须是volatile类型
};
#endif
thread.cpp
#include <QtCore>
#include <iostream>
#include "thread.h"
Thread::Thread()
{
stopped = false;//设置为false
}
void Thread::setMessage(const QString &message)
{
messageStr = message;
}
void Thread::run()
{
while (!stopped)
std::cerr << qPrintable(messageStr);
stopped = false;
std::cerr << std::endl;
}
void Thread::stop() //用stopped标识符来终止进程
{
stopped = true;
}
threaddialog.h //主程序函数 在这里面 启动和终止线程
#ifndef THREADDIALOG_H
#define THREADDIALOG_H
#include <QDialog>
#include "thread.h"
class Threaddialog:public QDialog
{
Q_OBJECT
public:
Threaddialog(QWidget *parent=0);
protected:
void closeEvent(QCloseEvent *event); //回收资源
private slots:
void startOrStopThreadA();
void startOrStopThreadB();
private:
Thread threadA;
Thread threadB;
QPushButton *threadAButton;
QPushButton *threadBButton;
QPushButton *quitButton;
};
#endif // THREADDIALOG_H
threaddialog.cpp
#include <QtGui>
#include "threaddialog.h"
Threaddialog::Threaddialog(QWidget *parent):QDialog(parent)
{
threadA.setMessage("A");
threadB.setMessage("B");
threadAButton=new QPushButton(tr("Start A"));
threadBButton=new QPushButton(tr("Start B"));
quitButton=new QPushButton(tr("Quit"));
quitButton->setDefault(true);
connect(threadAButton,SIGNAL(clicked()),this,SLOT(startOrStopThreadA()));
connect(threadBButton,SIGNAL(clicked()),this,SLOT(startOrStopThreadB()));
connect(quitButton,SIGNAL(clicked()),this,SLOT(close()));
QHBoxLayout *mainLayout= new QHBoxLayout;
mainLayout->addWidget(threadAButton);
mainLayout->addWidget(threadBButton);
mainLayout->addWidget(quitButton);
setLayout(mainLayout);
}
void Threaddialog::startOrStopThreadA()
{
if(threadA.isRunning())
{
threadA.stop(); //终止线程
threadAButton->setText(tr("Start A"));
}
else
{
threadA.start(); //启动线程,线程会去执行其中的run()函数
threadAButton->setText(tr("Stop A"));
}
}
void Threaddialog::startOrStopThreadB()
{
if(threadB.isRunning())
{
threadB.stop();
threadBButton->setText(tr("Start B"));
}
else
{
threadB.start();
threadBButton->setText(tr("stop B"));
}
}
void Threaddialog::closeEvent(QCloseEvent *event) //回收资源
{
threadA.stop();
threadB.stop();
threadA.wait();
threadB.wait();
event->accept();
}
main.cpp
#include <QApplication>
#include "threaddialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
ThreadDialog dialog;
dialog.show();
return app.exec();
}