1.示例计算从1加到n解决方案例如n1000所以拆分成[1, 1000] [1, 300] [301, 600] [601, 1000]#include QtCore/QCoreApplication #include QDebug #include QThread #include QObject class Calculator : public QObject { protected: int m_begin; int m_end; int m_result; void run() { qDebug() objectName() : run() begin; for(int im_begin; im_end; i) { m_result i; } qDebug() objectName() : run() end; } public: Calculator(int begin, int end) { m_begin begin; m_end end; m_result 0; } void work() { run(); } int result() { return m_result; } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() main begin; Calculator cal1(1, 300); Calculator cal2(301, 600); Calculator cal3(601, 1000); cal1.setObjectName(cal1); cal2.setObjectName(cal2); cal3.setObjectName(cal3); cal1.work(); cal2.work(); cal3.work(); int result cal1.result() cal2.result() cal3.result(); qDebug() result result; qDebug() main end; return QCoreApplication::exec(); }运行结果main begincal1 : run() begincal1 : run() endcal2 : run() begincal2 : run() endcal3 : run() begincal3 : run() endresult 500500main end不能实现并行运行所以我们就用到线程同步的概念t.start(); //创建并启动子线程t.wait(); //等待子线程执行结束#include QtCore/QCoreApplication #include QDebug #include QThread #include QObject class Calculator : public QThread { protected: int m_begin; int m_end; int m_result; void run() { qDebug() objectName() : run() begin; for(int im_begin; im_end; i) { m_result i; msleep(10); } qDebug() objectName() : run() end; } public: Calculator(int begin, int end) { m_begin begin; m_end end; m_result 0; } void work() { run(); } int result() { return m_result; } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() main begin; Calculator cal1(1, 300); Calculator cal2(301, 600); Calculator cal3(601, 1000); cal1.setObjectName(cal1); cal2.setObjectName(cal2); cal3.setObjectName(cal3); cal1.start(); cal2.start(); cal3.start(); cal1.wait(); cal2.wait(); cal3.wait(); int result cal1.result() cal2.result() cal3.result(); qDebug() result result; qDebug() main end; return QCoreApplication::exec(); }运行结果main begincal1 : run() begincal2 : run() begincal3 : run() begincal2 : run() endcal1 : run() endcal3 : run() endresult 500500main end