QT开发中文网

写一个qt窗体应用程序,要求三个线程,要求同时跑,第一个线程计算一万个1相乘,第二个线程计算2000个2相加,第三个线程计算30000个3相加,在线程都计算完成后将结果进行相加,输出。

以下是一个使用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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=6270

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?