首页 > 学院 > 开发设计 > 正文

多线程

2019-11-08 20:12:05
字体:
来源:转载
供稿:网友
写一个线程类,继承QThread//workthread.h#ifndef WORKTHREAD_H#define WORKTHREAD_H#include <QThread>class WorkThread : public QThread{ Q_OBJECTpublic: WorkThread();PRotected: //重写run函数,业务逻辑写在该函数中 void run(); };#endif // WORKTHREAD_H//workthread.cpp#include "workthread.h"#include <QtDebug>WorkThread::WorkThread(){}void WorkThread::run(){ while(true) { for(int n=0;n<10;n++) qDebug()<<n<<n<<n<<n<<n<<n<<n<<n; }}

2、编写一个自定义Dialog

//threaddlg.h#ifndef THREADDLG_H#define THREADDLG_H#include <QDialog>#include <QPushButton>#include "workthread.h"#define MAXSIZE 5class ThreadDlg : public QDialog{ Q_OBJECTpublic: ThreadDlg(QWidget *parent = 0); ~ThreadDlg(); private: QPushButton *startBtn; QPushButton *stopBtn; QPushButton *quitBtn;public slots: void slotStart(); void slotStop();private: WorkThread *workThread[MAXSIZE];};#endif // THREADDLG_H//threaddlg.cpp#include "threaddlg.h"#include <QHBoxLayout>ThreadDlg::ThreadDlg(QWidget *parent) : QDialog(parent){ setWindowTitle(tr("线程")); startBtn = new QPushButton(tr("开始")); stopBtn = new QPushButton(tr("停止")); quitBtn = new QPushButton(tr("退出")); QHBoxLayout *mainLayout = new QHBoxLayout(this); mainLayout->addWidget(startBtn); mainLayout->addWidget(stopBtn); mainLayout->addWidget(quitBtn); connect(startBtn,SIGNAL(clicked()),this,SLOT(slotStart())); connect(stopBtn,SIGNAL(clicked()),this,SLOT(slotStop())); connect(quitBtn,SIGNAL(clicked()),this,SLOT(close()));}ThreadDlg::~ThreadDlg(){}void ThreadDlg::slotStart(){ for(int i=0;i<MAXSIZE;i++) { workThread[i]=new WorkThread(); } for(int i=0;i<MAXSIZE;i++) { workThread[i]->start(); //启动线程 } startBtn->setEnabled(false); stopBtn->setEnabled(true);}void ThreadDlg::slotStop(){ for(int i=0;i<MAXSIZE;i++) { workThread[i]->terminate(); //终止线程,但是并不会马上,要根据系统调度 workThread[i]->wait(); //阻塞线程,等待系统终止线程 } startBtn->setEnabled(true); stopBtn->setEnabled(false);}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表