关于多线程

一.多线程优势:

1.多线程可以提高应用程序的响应速度;

2.使多CPU系统更加有效,当线程数不大于cpu数目时,操作系统可以调度不同的线程运行于不同的cpu上;

3.改善程序结构;

二.多线程的特点

1.多线程的行为无法预期;

2.多线程的执行顺序无法保证;

3.多线程的切换可能发生在任何时刻,任何地点;

例子:多个线程执行相同的动作;

#include "threaddlg.h"
#include "ui_threaddlg.h"
#include<QThread>
#include"thread.h"
threadDlg::threadDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::threadDlg)
{
    ui->setupUi(this);
}

threadDlg::~threadDlg()
{
    delete ui;
}

void threadDlg::on_start_clicked()
{
    for(int i=0;i<MAXSIZE; i++)
       {
         nthread[i]=new Thread();
       }
    for(int i=0;i<MAXSIZE;i++)
    {
        nthread[i]->start();
    }
   ui->start->setEnabled(false);
   ui->stop->setEnabled(true);
}

void threadDlg::on_stop_clicked()
{
    for(int i=0;i<MAXSIZE; i++)
       {
         nthread[i]->terminate();
         nthread[i]->wait();
       }

   ui->start->setEnabled(true);
   ui->stop->setEnabled(false);

}
#include "thread.h"
#include<QDebug>
Thread::Thread()
{

}
void Thread ::run()
{
    for(int i=0;i<10;i++)
    {
      qDebug()<<i<<i<<i<<i<<i<<i<<i<<i<<i<<i ;

    }
}

执行结果:

线程数为1:

 线程数大于1:

 多线程输出的结果是乱序的,说明了多线程的执行顺序无法保证的特点;

这个简单的例子便于理解多线程的概念,操作,以及简单的使用;

原文地址:https://www.cnblogs.com/whitewn/p/6944909.html