qt学习笔记———线程

8 篇文章 0 订阅

一、设计说明

实现线程的启动和停止。点击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方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值