一、设计说明
实现线程的启动和停止。点击Start A后按钮文本显示为Stop ,A线程启动,并且循环打印"threadA",点击Start B后按钮文本显示为Stop ,B线程启动,并且循环打印"threadB",A,B线程互不影响。
二、效果演示
QT线程
三、代码
1.widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "mythread.h"//添加头文件
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_clicked();
void on_pushButtonB_clicked();
private:
Ui::Widget *ui;
MyThread threadA,threadB;//线程对象
};
#endif // WIDGET_H
2.widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
threadA.setMsg("threadA");//设置threadA的msg
threadB.setMsg("threadB");
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//启动/停止线程
if(threadA.isRunning())//线程正在运行
{
ui->pushButton->setText("Start A");
//关闭线程
threadA.stop();//停止线程
threadA.wait();//等线程结束
}
else //线程已经停止
{
ui->pushButton->setText("Stop");
threadA.start();//启动线程
}
}
void Widget::on_pushButtonB_clicked()
{
//启动/停止线程
if(threadB.isRunning())//线程正在运行
{
ui->pushButtonB->setText("Start B");
//关闭线程
threadB.stop();//停止线程
threadB.wait();//等线程结束
}
else //线程已经停止
{
ui->pushButtonB->setText("Stop");
threadB.start();//启动线程
}
}
3.mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QThread>
#include <QMutex>
class MyThread : public QThread
{
Q_OBJECT//使之支持信号与槽
public:
MyThread(QObject *parent = Q_NULLPTR );
void setMsg(QString);//设置msg的方法
void stop();
protected:
void run();
private:
QString msg;
bool stoped;
QMutex mutex;//构造互斥锁对象
};
#endif // MYTHREAD_H
4.mythread.cpp
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
stoped = false;//线程是运行的
}
void MyThread::stop()//停止线程
{
mutex.lock();//加锁
stoped = true;
mutex.unlock();//解锁
}
void MyThread::setMsg(QString msg)
{
this->msg = msg;
}
void MyThread::run()//重写基类QThread的run方法
{
forever{//while(1)
mutex.lock();//加锁
if(stoped)
{
stoped = false;
mutex.unlock();//解锁
break;
}
mutex.unlock();//解锁
qDebug() << msg;
QThread::sleep(1);//ls
}
}
四、总结
涉及知识点:第一:两个线程互斥,这里使用到了互斥锁,使用前加锁,使用后解锁。第二:重写基类QThread的run方法。