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 输出的结果。

  • 相关阅读:
    leetcode 343. Integer Break(dp或数学推导)
    leetcode 237. Delete Node in a Linked List
    msdtc不可用
    常用反编译软件
    重建索引
    JAVA知识库
    DATAGRID显示序号
    VFLEXGRID8控件注册
    黑马2017年java就业班全套视频教程
    mybatis从入门到精通
  • 原文地址:https://www.cnblogs.com/YouLing0809/p/6735718.html
Copyright © 2011-2022 走看看