标签:
方式2:在QThread中使用WorkObject
1.创建WorkObject
1 #include <QObject> 2 #include <QDebug> 3 #include <QThread> 4 5 #define DEBUG(x) 6 { 7 qDebug()<<"class name:"<<x->metaObject()->className()<<"\n" 8 <<"function:"<<__func__<<"\n" 9 <<"thread id = "<<QThread::currentThreadId() 10 <<"\n--------------------------------------------------"; 11 }12 13 class WorkObject : public QObject 14 { 15 Q_OBJECT 16 Q_DISABLE_COPY(WorkObject) 17 18 public: 19 static WorkObject *getInstance() 20 { 21 static WorkObject instance; 22 return &instance; 23 } 24 25 void start(){DEBUG(this);} 26 27 private: 28 29 explicit WorkObject(QObject *parent = 0) 30 :QObject(parent) 31 {} 32 };
2.创建WorkThread
1 #include <QThread> 2 3 #include "workobject.h" 4 5 class WorkThread : public QThread 6 { 7 public: 8 WorkThread(QObject *parent = 0) 9 :QThread(parent) 10 {} 11 12 protected: 13 void run() 14 { 15 DEBUG(this); 16 WorkObject *pWork = WorkObject::getInstance(); 17 pWork->start(); 18 } 19 };
3.创建ManagerObject
1 #include <QObject> 2 3 #include "workobject.h" 4 #include "workthread.h" 5 6 class ManagerObject : public QObject 7 { 8 Q_OBJECT 9 public: 10 explicit ManagerObject(QObject *parent = 0) 11 :QObject(parent) 12 {} 13 14 void start() 15 { 16 DEBUG(this); 17 WorkObject *pObj = WorkObject::getInstance(); 18 pObj->start(); 19 } 20 21 void threadRun() 22 { 23 DEBUG(this); 24 WorkThread *pThread =new WorkThread; 25 pThread->start(); 26 } 27 };
4.main.cpp
1 #include <QCoreApplication> 2 #include <QDebug> 3 4 #include "managerobject.h" 5 #include "workthread.h" 6 7 8 int main(int argc, char *argv[]) 9 { 10 QCoreApplication a(argc, argv); 11 12 qDebug()<<"main thread id = "<<QThread::currentThreadId()<<"\n"; 13 ManagerObject k; 14 k.start(); 15 k.threadRun(); 16 17 //WorkThread *p = new WorkThread; 18 // p->start(); 19 20 return a.exec(); 21 }
5.运行结果
标签:
原文地址:http://www.cnblogs.com/Mach-he/p/5831500.html