一、摘要
刚开始学习QT的线程知识,有不正确的请指正。
二、创建线程的类,继承QThread
新建一个类,命名为MyThread,在MyThread.h中按照下列代码修改并添加缺少内容。
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QMutex>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void threadPause();
void threadResume();
protected:
//QThread的虚函数
//线程处理函数
//不能直接调用,通过start()间接调用
void run();
signals:
void isDone();
public slots:
private:
bool m_buttonState; //if pause m_buttonState=false;else m_buttonState=true;
int m_i;
QMutex m_mutex;//互斥量
};
#endif // MYTHREAD_H
三、添加线程类的实体函数
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
m_buttonState=true;
while(1)
{
m_mutex.lock();
m_i++;
qDebug()<<QString("the value of m_i is %1 ").arg(m_i);
m_mutex.unlock();
this->sleep(1);
}
}
void MyThread::threadPause()//暂停线程
{
qDebug()<<QString("pause :%1").arg(m_buttonState);
this->m_mutex.lock();
this->m_buttonState=false;
qDebug()<<QString("pause");
}
void MyThread::threadResume()//继续线程
{
qDebug()<<QString("resume :%1").arg(m_buttonState);
this->m_mutex.unlock();
this->m_buttonState=true;
qDebug()<<QString("resume");
}
四、启动线程、暂停线程、继续线程
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer> //定时器头文件
#include "mythread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void dealTimeout();//定时器槽函数
void dealDone();
void stopThread();//停止线程槽函数
void slotGrabFullScreen();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::Widget *ui;
QTimer *myTimer;
MyThread *thread;//线程对象
};
#endif // WIDGET_H
widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QThread>
#include <QDebug>
#include <QDateTime>//系统时间的头文件
#include <Windows.h>
#include <QScreen>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
myTimer = new QTimer(this);
//只要定时器启动,自动触发timerout()
connect(myTimer, &QTimer::timeout, this, &Widget::dealTimeout);
//分配空间,指定父对象
thread = new MyThread(this);
connect(thread, &MyThread::isDone, this, &Widget::dealDone);
//当按窗口右上角X时,窗口触发destroyed()
connect(this, &Widget::destroyed, this, &Widget::stopThread);
}
void Widget::stopThread()//退出应用执行关闭线程
{
thread->threadPause();//暂停线程
qDebug() << "开始关闭线程";
thread->quit();//停止线程
thread->wait();//等待线程处理完手头工作
}
void Widget::dealTimeout()//LCD控件显示
{
static int i = 0;
i++;
ui->lcdNumber->display(i);
}
void Widget::dealDone()
{
qDebug() << "it is over";
myTimer->stop();
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()//开始线程
{
//如果定时器没有工作
if(myTimer->isActive() == false)
{
myTimer->start(100);
qDebug() << "start";
}
thread->start();//启动线程
}
void Widget::on_pushButton_2_clicked()//暂停线程
{
thread->threadPause();
}
void Widget::on_pushButton_3_clicked()//线程继续
{
thread->threadResume();
}