1.mythread.h(头文件)
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QObject *parent = nullptr);
~MyThread();
void setStopIsActive(bool flag);
protected:
void run();
signals:
//自定义信号 传递数据
void curNumber(int num);
private:
bool isStop;
};
#endif // MYTHREAD_H
2.mythread.cpp(CPP文件)
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent)
: QThread(parent)
{
isStop = false;
}
MyThread::~MyThread()
{
}
void MyThread::setStopIsActive( bool flag )
{
isStop = flag;
}
void MyThread::run()
{
qDebug()<<"curThread address is :"<<QThread::currentThread()<<endl;
int num =0;
while(isStop == false)
{
if (isStop == true)
{
break;
}
emit curNumber(num++);
if (num == 1000)
{
break;
}
QThread::usleep(2);
}
qDebug()<<"run() is over now is exit"<<endl;
}
3.mysecondthread.h(头文件)
#ifndef MYSECONDTHREAD_H
#define MYSECONDTHREAD_H
#include <QThread>
class MySecondthread : public QThread
{
Q_OBJECT
public:
MySecondthread(QObject *parent= nullptr);
~MySecondthread();
void setStopIsActive(bool flag);
protected:
void run();
signals:
//自定义信号 传递数据
void curNumber(int num);
private:
bool isStop;
};
#endif // MYSECONDTHREAD_H
4…mysecondthread.cpp(CPP文件)
#include "mysecondthread.h"
#include <QDebug>
MySecondthread::MySecondthread(QObject *parent)
: QThread(parent)
{
isStop = false;
}
MySecondthread::~MySecondthread()
{
}
void MySecondthread::setStopIsActive( bool flag )
{
isStop = flag;
}
void MySecondthread::run()
{
qDebug()<<"curthread address is :"<<QThread::currentThread()<<endl;
int num =1000;
while(isStop == false)
{
if (isStop == true)
{
break;
}
emit curNumber(num--);
if (num == 0)
{
break;
}
QThread::usleep(2);
}
qDebug()<<"run() is over now is exit"<<endl;
}
5.主程序
#include "testaboutthread.h"
#include "mythread.h"
#include "mysecondthread.h"
#include <QDebug>
TestAboutThread::TestAboutThread(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
qDebug()<<"main thread address:"<<QThread::currentThread();
//创建子线程1
MyThread* subThread = new MyThread;
connect(subThread, &MyThread::curNumber, this, [=](int num)
{
qDebug()<<"first:"<<num<<endl;
ui.lcdNumber->display(num);
});
connect(ui.pushButton, &QPushButton::clicked, this, [=]()
{
//启动子线程1
subThread->setStopIsActive(false);
subThread->start();
});
//创建子线程2
MySecondthread* subSecondThread = new MySecondthread;
connect(subSecondThread, &MySecondthread::curNumber, this, [=](int num)
{
qDebug()<<"second:"<<num<<endl;
ui.lcdNumber02->display(num);
});
connect(ui.closeButton, &QPushButton::clicked, this, [=]()
{
//启动子线程2
subSecondThread->setStopIsActive(false);
subSecondThread->start();
});
connect(ui.closethreadButton, &QPushButton::clicked, this,[=]()
{
//关闭线程
subThread->setStopIsActive(true);
subSecondThread->setStopIsActive(true);
});
}
TestAboutThread::~TestAboutThread()
{
}
6.图示
左边开始按钮 控制左边的数字显示
右边开始按钮控制右边的数字显示
关闭按钮 可以停止两边的数字显示