一起看代码来玩玩QT之20 Thread(线程)

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);

    void foo()
    {
        qDebug() << QThread::currentThread();
    }
    void run()
    {
        foo();
        qDebug() << "thread is run";

    }

signals:

public slots:

};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"

MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
}


worker.h

#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QThread>
#include <QDebug>
class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);

    QThread _thread;

    bool event(QEvent *ev)
    {
        qDebug() << "event:"<<QThread::currentThread();
        return QObject::event(ev);
    }

signals:

public slots:
    void doWork()
    {
        // do ......
        qDebug() << QThread::currentThread();
    }
};

#endif // WORKER_H

worker.cpp

#include "worker.h"

Worker::Worker(QObject *parent) :
    QObject(parent)
{
   // this->moveToThread(&_thread);
    _thread.start();
    connect(&_thread, SIGNAL(finished()), this, SLOT(deleteLater()));
}

main.cpp

#include <QCoreApplication>
#include "mythread.h"
#include "worker.h"
#include <QTimer>
#include<QThread>
int main(int argc, char* argv[])
{
    QCoreApplication app(argc, argv);

#if 0
    MyThread thread;
    thread.start();

    thread.foo();
#endif

    qDebug() << "main thread is"<<QThread::currentThread();
    Worker* worker = new Worker();
#if 0	
	QThread thread;
	worker->moveToThread(&thread);
	thread.start(); //线程有它自己的消息机制,调用even()时 ……
#endif	
	
    QTimer* timer = new QTimer;

    QObject::connect(timer, SIGNAL(timeout()), worker, SLOT(doWork()));
    timer->setInterval(1000);
    timer->start();

    return app.exec();
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值