1.run模式更适合于多开
//.cpp
#pragma once
#include <QThread>
class SimpleThreadOne : public QThread //继承Thread
{
public:
int para1;
QString para2;
SimpleThreadOne(int input1,QString input2):para1(input1),para2(input2)//传参
{
};
void run();
};
//.h
#include "simplethreadone.h"
void SimpleThreadOne::run()
{
while (true)
{
sleep(1000);//费时主程序
}
}
//main
#include "mainwindow.h"
#include <QApplication>
#include "simplethreadone.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QString a="fast";
int b=1;
//开一百个子线程
for(int i=0;i<100;i++)
{
SimpleThreadOne *SThread = new SimpleThreadOne(b,a);
SThread->start();
}
return a.exec();
}
2.movetoThread Qt推荐 更安全
//.h
#pragma once
#include <QObject>
class SimpleThreadTwo : public QObject//继承QObject
{
Q_OBJECT
public:
explicit SimpleThreadTwo(QObject *parent = nullptr);
public slots:
void doSomething(QString para1,int para2);
};
//.cpp
#include "simplethreadtwo.h"
#include <unistd.h>
SimpleThreadTwo::SimpleThreadTwo(QObject *parent) : QObject(parent)
{}
void SimpleThreadTwo::doSomething(QString para1,int para2)
{
sleep(2);
}
//MainWindows.h
#pragma once
#include <QMainWindow>
#include "simplethreadtwo.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void SendStart(void);
signals:
void Signal1(QString input1,int input2);
private:
Ui::MainWindow *ui;
};
//MainWindows.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
QThread* m_objThread=new QThread();;
SimpleThreadTwo* m_ThreadTwo = new SimpleThreadTwo();//new 多线程对象
m_ThreadTwo->moveToThread(m_objThread);//movetoThread
connect(m_objThread,&QThread::finished,m_objThread,&QObject::deleteLater);//停止后删除
connect(this,&MainWindow::Signal1,m_ThreadTwo,&SimpleThreadTwo::doSomething);//参数要对应 最多五个
m_objThread->start();//一定记得start
//开始执行
QString a="XX";
int b=1;
emit Signal1(a,b);
}
MainWindow::~MainWindow()
{
delete ui;
}