Qt之多线程

#include <QtGui/QApplication>
#include <qthread.h>
#include <windows.h>

#include "mainwindow.h"

/*创建一个线程类*/
class MyThread1 : public QThread   //这里创建一个线程的类,                                 
{                                 // 该类继承于QThread,其中只有一个函数run
    public:  
     virtual void run();    //run函数式该线程的执行函数,也就是说,
                            //只要这个线程被启动,那么该函数就会被调用
};

/*一个线程的主函数,循环打印一句话*/
void MyThread1::run()            
{
    while(1)
    {
        qDebug("hello");   //通过qDebug打印hello
        Sleep(1000);       //延迟1S
    }
}

/*创建另一个线程类*/
class MyThread2 : public QThread
{
    public:
        virtual void run();

};

/*一个线程的主函数,循环打印一句话*/
void MyThread2::run()
{
    while(1)
    {
        qDebug("word");
        Sleep(1000);
    }
}

int main(int argc, char *argv[])
{

    /*定义一个线程,并且启动该线程*/
    MyThread1 thread1;       //这里通过刚才定义的第一个类,实例化一个对象
    thread1.start();         //这里启动该线程,然后run函数开始执行。
                             //(和linux下的那个线程函数差不多一个意思)

    /*定义另一个线程,并且启动该线程*/
    MyThread2 thread2;
    thread2.start();

    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/u014252478/article/details/80743696
今日推荐