首先设计一个qt界面,包含4个button按钮,2个lineEdit,如图所示
界面测试多线程功能如下:
Pushbutton1和stop1按钮控制线程1的开始和结束,线程中使用while true死循环,输出从0开始,间隔10ms加1;Pushbutton2和stop2按钮控制线程2的开始和结束,线程中使用while true死循环,输出从0开始,间隔100ms加1。
mainwindow.h文件如下:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
int i = 0;
void f1();
int f1_end_flag = 0;
void f2();
int j = 0;
int f2_end_flag = 0;
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_stop1_clicked();
void on_pushButton_stop2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
f1_end_flag和f2_end_flag是线程1和线程2停止标志。
mainwindow.cpp文件如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Windows.h"
#include <QString>
#include <QtConcurrent/QtConcurrent>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::f1()
{
f1_end_flag = 0;
while (1) {
i++;
Sleep(10);
ui->lineEdit->setText(QString::number(i));
if (f1_end_flag == 1)
{
break;
}
}
}
void MainWindow::f2()
{
f2_end_flag = 0;
while (1) {
j++;
Sleep(100);
ui->lineEdit_2->setText(QString::number(j));
if(f2_end_flag == 1)
{
break;
}
}
}
void MainWindow::on_pushButton_clicked()
{
QtConcurrent::run(this,&MainWindow::f1);
}
void MainWindow::on_pushButton_2_clicked()
{
QtConcurrent::run(this,&MainWindow::f2);
}
void MainWindow::on_pushButton_stop1_clicked()
{
f1_end_flag = 1;
}
void MainWindow::on_pushButton_stop2_clicked()
{
f2_end_flag = 1;
}
运行结果如下: