QT:QThread:重写run函数

问题描述:QThread的使用方法2重写run函数

解决:

创建一个集成QThread的类thread

thread.h:

run()函数则是新线程的入口,run()函数退出意味着线程的退出。

stop()函数:线程停止

cpp 复制代码
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <iostream>
#include <QDebug>

class thread: public QThread
{
    Q_OBJECT
public:
    thread();
    void stop();

protected:
    void run();

    void printMessage();

private:
    volatile bool stopped;


};

#endif // THREAD_H

thread.cpp

cpp 复制代码
#include "thread.h"
#include <QDebug>
thread::thread()
{

    stopped =false;

}
void thread::run()
{
    qDebug() << "子线程id:" << QThread::currentThreadId();
    while(!stopped)
    {
        printMessage();
    }
    stopped = false;
}

void thread::stop()
{
    qDebug()<<"进程已经停止";
    stopped = true;
}

void thread::printMessage()
{
    qDebug()<< "hello";
    usleep(5);
}

mainwindow.h:两个按钮的槽函数一个是开启线程一个是关闭线程

cpp 复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include <iostream>
#include <QDebug>
#include <QMainWindow>
#include <QCloseEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();


private:
    Ui::MainWindow *ui;
protected:
    void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H

mainwindow.cpp:

closeEvent:QThread的安全销毁

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "thread.h"
thread  myThread;
//thread  myThread1;
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug() << "主线程id:" << QThread::currentThreadId();

}
//关闭线程
void MainWindow::on_pushButton_clicked()
{
    myThread.stop();

}
//开启线程

void MainWindow::on_pushButton_2_clicked()
{
    myThread.start();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    myThread.stop();
    myThread.wait();
    event->accept();
}


MainWindow::~MainWindow()
{
    delete ui;

}
相关推荐
m0_471199634 分钟前
【场景】笛卡尔积
开发语言·前端·javascript
Brookty7 分钟前
Java并发编程核心的基础知识
java·开发语言·java-ee·多线程·线程安全
开始了码7 分钟前
UDP 协议详解与 Qt 实战应用
qt·网络协议·udp
hellotutu8 分钟前
Java 读取 Excel 文件
java·开发语言·excel
胡萝卜3.09 分钟前
构建安全的C++内存管理体系:从RAII到智能指针的完整解决方案
运维·开发语言·c++·人工智能·安全·智能指针·raii
MSTcheng.10 分钟前
【C++】如何快速实现一棵支持key或key-value的二叉搜索树?关键技巧一文掌握!
开发语言·c++·算法·二叉搜索树
ByNotD0g11 分钟前
Go 泛型 in 1.25
开发语言·后端·golang
野生风长13 分钟前
从零开始的c语言:指针高级应用(下)(回调函数,qsort函数模拟实现, strlen和sizeof)
java·c语言·开发语言·c++·算法
chao18984416 分钟前
C# 实现画板源码
开发语言·c#
lly20240620 分钟前
Eclipse 创建 Java 包
开发语言