多线程的创建与运行
关于多线程的使用无论是C、C++还是Java等其他语言都用的比较多
以下以QT的C++为例创建并运行多线程;
并测试是否多线程同时运行(成功标志为两个无序间隔输出)
头文件:
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <iostream>
class thread:public QThread
{
Q_OBJECT
public:
thread();
void setMessage(QString message);
void stop();
int flag = 0;
protected:
void run();
void printMessage();
void printMessage1();
private:
QString messageStr;
volatile bool stopped;
};
#endif // THREAD_H
源文件:
#include "thread.h"
#include <QDebug>
thread::thread(){
}
void thread::run(){
if(flag == 0)
printMessage();
else
printMessage1();
}
void thread::stop(){
}
void thread::setMessage(QString message){
messageStr = message;
}
void thread::printMessage(){
for(int i=5;i>0;i--){
qDebug()<<i;
}
qDebug()<<messageStr;
}
void thread::printMessage1(){
for(int i=5;i>0;i--){
qDebug()<<"g";
}
qDebug()<<messageStr;
}
main文件:
#include "thread.h"
int main(){
thread thread1;
thread thread2;
thread1.flag = 1;
thread2.flag = 0;
thread1.setMessage("A");
thread2.setMessage("B");
thread1.start();
thread2.start();
thread1.wait();
thread2.wait();
}
运行成功标志:
5
4
g
3
g
2
g
1
g
“B”
g
“A”