您可以连接 timeout() 信号QTimer
到适当的插槽,并调用start()
。从那时起,定时器将以恒定的时间间隔发出 timeout() 信号。但这两个计时器都在主线程和主事件循环中运行。所以你不能称它为多线程。因为两个插槽不同时运行。它们一个接一个地运行,如果一个阻塞主线程,另一个将永远不会被调用。
您可以通过一些用于不同任务的类来拥有一个真正的多线程应用程序,这些任务应该同时完成并使用QObject::moveToThread
更改对象的线程关联性:
QThread *thread1 = new QThread();
QThread *thread2 = new QThread();
Task1 *task1 = new Task1();
Task2 *task2 = new Task2();
task1->moveToThread(thread1);
task2->moveToThread(thread2);
connect( thread1, SIGNAL(started()), task1, SLOT(doWork()) );
connect( task1, SIGNAL(workFinished()), thread1, SLOT(quit()) );
connect( thread2, SIGNAL(started()), task2, SLOT(doWork()) );
connect( task2, SIGNAL(workFinished()), thread2, SLOT(quit()) );
//automatically delete thread and task object when work is done:
connect( thread1, SIGNAL(finished()), task1, SLOT(deleteLater()) );
connect( thread1, SIGNAL(finished()), thread1, SLOT(deleteLater()) );
connect( thread2, SIGNAL(finished()), task2, SLOT(deleteLater()) );
connect( thread2, SIGNAL(finished()), thread2, SLOT(deleteLater()) );
thread1->start();
thread2->start();
注意Task1
and Task2
继承自QObject
.