zoukankan      html  css  js  c++  java
  • Qt的多线程总结以及使用(一)

    Qt提供QThread类以进行多任务的处理。Qt提供的线程可以做到单个进程做不到的事情。在这里实现最简单的一个多线程。最简单的线程的基类为QThread,然后需要重写QThread的run(),在run()函数中实现的功能就是在线程中实现的功能。代码如下:

    YLThread.h

    #ifndef YLTHREAD_H
    #define YLTHREAD_H
    #include <QThread>
    
    class YLThread : public QThread
    {
     Q_OBJECT
    public:
     YLThread();
    
    protected:
     void run();
    public:
     //用来打印数据
     void setValue(int num);
    private:
     int printNum;
    };
    
    #endif // YLTHREAD_H
    

    YLThread.cpp

    #include "YLThread.h"
    #include <QDebug>
    YLThread::YLThread()
    {
    
    }
    
    void YLThread::run(){
    
     //打印数据
     for(int i =0;i < 5;i++){
     p, li { white-space: pre-wrap; }
    
    qDebug()<<QStringLiteral("value=%1输出:-----").arg(printNum)<<i+printNum;
     }
    }
    void YLThread::setValue(int num)
    {
     printNum = num;
    }
    

    main.cpp

    #include <QCoreApplication>
    #include <QDebug>
    #include "YLThread.h"
    int main(int argc, char *argv[])
    {
     QCoreApplication a(argc, argv);
    
     YLThread* thread01 = new YLThread() ;
     thread01->setValue(10);
    
     YLThread* thread02 = new YLThread() ;
     thread02->setValue(20);
    
     thread01->start();
     thread02->start();
    
     return a.exec();
    }
    

    以上代码是实现了最简单的多线程的操作,运行结果如下:

    636D13F7-604B-4F6D-A53A-DC53C3557042.png
    输出结果中,带红框的是是value =10的情况时的线程,不带红框的是value =20 输出的结果。

  • 相关阅读:
    二人组
    对于软件工程的理解
    shell 远程链接
    shell变量
    shell教程
    正则表达式--练习
    git--版本库
    git-版本回退
    git--时光穿梭
    git安装
  • 原文地址:https://www.cnblogs.com/YouLing0809/p/6735718.html
Copyright © 2011-2022 走看看