当前位置 博文首页 > 木木木 的博客:Qt开发之路30---4种常用的多线程实现方式
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread: public QThread
{
Q_OBJECT
public:
MyThread();
~MyThread();
protected:
void run(); //虚函数重构
public:
void stop();
private:
bool m_bFlag;
};
#endif // MYTHREAD_H
#include "mythread.h"
#include <QDebug>
MyThread::MyThread()
{
}
MyThread::~MyThread()
{
}
void MyThread::run()
{
m_bFlag = true;
while (m_bFlag) {
qDebug() << "thread id: "<<QThread::currentThreadId();
QThread::msleep(100);
}
}
void MyThread::stop()
{
m_bFlag = false;
}
#include "mythread.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyThread *myThread = new MyThread();
myThread->start(); //开启线程
return a.exec();
}
#ifndef MYWORK_H
#define MYWORK_H
#include <QObject>
class MyWork : public QObject
{
Q_OBJECT
public:
explicit MyWork(QObject *parent = 0);
signals:
public slots:
void doWork();
};
#endif // MYWORK_H
#include "mywork.h"
#include <QDebug>
#include <QThread>
MyWork::MyWork(QObject *parent) : QObject(parent)
{
}
void MyWork::doWork()
{
for(int i = 0; i < 1000; i++){
qDebug() << "thread id: "<<QThread::currentThreadId();
}
}
#include "mywork.h"
#include <QApplication>
#include <QThread>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWork *myWork = new MyWork();
QThread *myThread = new QThread();
QObject::connect(myThread,SIGNAL(started()),myWork,SLOT(doWork()));
QObject::connect(myThread,SIGNAL(finished()),myWork,SLOT(deleteLater()));
QObject::connect(myThread,SIGNAL(finished()),myThread,SLOT(deleteLater()));
myWork->moveToThread(myThread);
myThread->start();
return a.exec();
}
class Runnable:public QRunnable
{
//Q_OBJECT Qrunnable不是QObject的子类。
public:
Runnable();
~Runnable();
void run();
};
Runnable::Runnable():QRunnable()
{
}
Runnable::~Runnable()
{
cout<<"~Runnable()"<<endl;
}
void Runnable::run()
{
cout<<"Runnable::run()thread :"<<QThread::currentThreadId()<<endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Runnable runObj;
QThreadPool::globalInstance()->start(&runObj);
returna.exec();
}
#include <QApplication>
#include <QThread>
#include <QtConcurrent/QtConcurrent>
void myPrint(QString str)
{
qDebug()<<str;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString str = "123";
QtConcurrent::run(myPrint,str);
return a.exec();
}
上一篇:Qt开发之路29—UDP 与 TCP区别(Socket通信)
下一篇:Qt开发之路31—Qt程序自动打包