以下是一个使用Qt框架编写的窗体应用程序,其中包含三个线程,分别计算一万个1相乘、2000个2相加和30000个3相加,并在所有线程计算完成后将结果相加并输出。
#include <QtWidgets>
class WorkerThread : public QThread
{
public:
explicit WorkerThread(QObject *parent = nullptr) : QThread(parent), result(0) {}
void run() override {
if (threadId() == 1) {
// 计算一万个1相乘
for (int i = 0; i < 10000; ++i) {
result *= 1;
}
} else if (threadId() == 2) {
// 计算2000个2相加
for (int i = 0; i < 2000; ++i) {
result += 2;
}
} else if (threadId() == 3) {
// 计算30000个3相加
for (int i = 0; i < 30000; ++i) {
result += 3;
}
}
emit calculationFinished(result);
}
signals:
void calculationFinished(int result);
private:
int result;
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
QLabel *resultLabel = new QLabel(this);
QPushButton *startButton = new QPushButton("Start", this);
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(resultLabel);
layout->addWidget(startButton);
QWidget *centralWidget = new QWidget(this);
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
connect(startButton, &QPushButton::clicked, this, &MainWindow::startCalculation);
connect(&thread1, &WorkerThread::calculationFinished, this, &MainWindow::handleResult);
connect(&thread2, &WorkerThread::calculationFinished, this, &MainWindow::handleResult);
connect(&thread3, &WorkerThread::calculationFinished, this, &MainWindow::handleResult);
}
private slots:
void startCalculation() {
result = 0;
thread1.start();
thread2.start();
thread3.start();
}
void handleResult(int value) {
resultMutex.lock();
result += value;
resultMutex.unlock();
if (thread1.isFinished() && thread2.isFinished() && thread3.isFinished()) {
QMessageBox::information(this, "Calculation Finished", QString("The final result is: %1").arg(result));
}
}
private:
WorkerThread thread1;
WorkerThread thread2;
WorkerThread thread3;
int result;
QMutex resultMutex;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
#include "main.moc"
这个程序创建了一个主窗口,包含一个结果显示标签和一个开始按钮。点击开始按钮会启动三个线程进行计算,分别计算一万个1相乘、2000个2相加和30000个3相加,并在所有线程计算完成后将结果累加并显示在结果显示标签中。
内容由零声教学AI助手提供,问题来源于学员提问