工程设计准则
线程对象的生命周期 > 对应的线程生命周期
同步型线程设计
#ifndef SYNCTHREAD_H
#define SYNCTHREAD_H
#include <QThread>
class SyncThread : public QThread
{
Q_OBJECT
protected:
void run();
public:
explicit SyncThread(QObject *parent = 0);
~SyncThread();
};
#endif // SYNCTHREAD_H
#include "SyncThread.h"
#include <QDebug>
SyncThread::SyncThread(QObject *parent) :
QThread(parent)
{
}
void SyncThread::run()
{
qDebug() << "void SyncThread::run() tid = " << currentThreadId();
for(int i=0; i<3; i++)
{
qDebug() << "void SyncThread::run() i = " << i;
sleep(1);
}
qDebug() << "void SyncThread::run() end";
}
SyncThread::~SyncThread()
{
wait();
qDebug() << "SyncThread::~SyncThread() destroy thread object";
}
运行结果:
运用场合:线程的生命周期比较短 ,才可以采用这种方法。在对象的析构函数中等待线程结束
异步型线程设计
#ifndef ASYNCTHREAD_H
#define ASYNCTHREAD_H
#include <QThread>
class AsyncThread : public QThread
{
Q_OBJECT
protected:
void run();
explicit AsyncThread(QObject *parent = 0);
~AsyncThread();
public:
static AsyncThread* NewInstance(QObject *parent = 0);
};
#endif // ASYNCTHREAD_H
#include "AsyncThread.h"
#include <QDebug>
AsyncThread* AsyncThread::NewInstance(QObject *parent)
{
return new AsyncThread(parent);
}
AsyncThread::AsyncThread(QObject *parent) :
QThread(parent)
{
}
void AsyncThread::run()
{
qDebug() << "void AsyncThread::run() tid = " << currentThreadId();
for(int i=0; i<3; i++)
{
qDebug() << "void AsyncThread::run() i = " << i;
sleep(1);
}
qDebug() << "void AsyncThread::run() end";
deleteLater();
}
AsyncThread::~AsyncThread()
{
qDebug() << "AsyncThread::~AsyncThread() destroy thread object";
}
运行结果图:
运行场合:线程生命周期不可控(生命周期很长),事件循环必须打开 否则 删除不了对象的
如果在主事件循环停止后调用 deleteLater(),则不会删除该对象。 从 Qt 4.8 开始,如果在没有运行事件循环的线程中的对象上调用 deleteLater(),则该对象将在线程完成时被销毁。