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)
{
}
#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();
}