为什么使用线程;
为什么没使用quit():
QThread::quit()需要一个event loop才能生效;
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QThread>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Mythread;
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::Widget *ui;
Mythread *myThread;
};
class Mythread : public QThread
{
Q_OBJECT
public:
Mythread(QWidget *parent = nullptr)
{
Q_UNUSED(parent);
}
~Mythread()
{
qDebug()<<"线程销毁"<<endl;
}
//线程的耗时函数都写在run()函数里面;
void run() override{
qDebug()<<"mythread start!"<<endl;
sleep(5);
qDebug()<<"mythread end"<<endl;
/实现析构函数,防止内存泄露
deleteLater();
}
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
class Mythread;
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
myThread = new Mythread(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//延时查看效果
// while (1) {
// system("ping 192.168.1.1");
// break;
// }
/启动线程;
myThread->start();
/开启多线程;
Mythread *testThread = new Mythread(this);
testThread->start();
}
void Widget::on_pushButton_2_clicked()
{
//判断线程是否运行并;
if(myThread->isRunning())
{
终止线程:
myThread->terminate();
}
}