Qt5 使用 QThread 简单测试

目录 Content
[hide]

单线程在某些情况下会阻塞进程,这时候就需要另外开辟一个线程来处理这事儿,QThread 就是这个作用。

代码实现

新建一个console程序,然后添加一个类 mythread,基于 QThread。代码是参考 Qt 线程 :http://inching.org/2014/05/03/qt-thread/ 的。

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QtCore>

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);

protected:
    void run();

signals:

public slots:

};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"


MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
}

void MyThread::run()
{
    for( int count = 0; count != 20; ++count ){
          qDebug()<<count;
          sleep( 1 );

    }
    qDebug()<<"mythread finish!";
}

main.cpp

#include <QCoreApplication>
#include "mythread.h"

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

    MyThread thread;
    thread.start();
    //thread.wait();
    QThread::sleep( 2 );
    qDebug()<<"main thread here";

    return a.exec();
}

代码测试

运行后,可以看到是两个线程同时执行的

Qthread_test源码下载

扩展阅读

Leave a Reply

Your email address will not be published. Required fields are marked *