from PySide.QtCore import *
from PySide.QtGui import *
import time as t
class WorkerThread(QThread):
def _init_(self, mw):
super(WorkerThread, self)._init_(mw)
self.gameName = ""
def setGameName(self, currGameName):
self.gameName = currGameName
def run(self):
print self.gameName
class GG(object):
workerThread = WorkerThread()
def startThread(self,stringer):
self.workerThread.setGameName(stringer)
self.workerThread.start()
harro = GG()
harro.startThread("hello")
harro.startThread("hi")
t.sleep(60)
这只打印" hi"而不是"你好"。为什么不打印?如何更改它以便打印两个?
答案 0 :(得分:4)
第二次拨打startThread
会取消第一次。线程没有时间打印"你好"你再次称之为打印"嗨"。
您可以在QThread.wait()
之后调用QThread.start()
等待线程完成。
一个工作示例(同样,具有正确的标识):
class WorkerThread(QThread):
def _init_(self, mw):
super(WorkerThread, self)._init_(mw)
self.gameName = ""
def setGameName(self, currGameName):
self.gameName = currGameName
def run(self):
print self.gameName
class GG(object):
workerThread = WorkerThread()
def startThread(self,stringer):
self.workerThread.setGameName(stringer)
self.workerThread.start()
self.workerThread.wait()
harro = GG()
harro.startThread("hello")
harro.startThread("hi")
此示例将在线程运行时冻结用户界面。 因此,对于更复杂的任务,您应该使用信号和插槽机制。
答案 1 :(得分:0)
这个例子非常小,因为线程只做一件事(打印一个字符串),然后退出。如果你真的想要并行启动两个线程,你可以修改你的GG类来跟踪多个线程对象。
class WorkerThread(QThread):
def _init_(self, mw):
super(WorkerThread, self)._init_(mw)
self.gameName = ""
def setGameName(self, currGameName):
self.gameName = currGameName
def run(self):
print self.gameName
class GG(object):
workerThreads = []
def startThread(self,stringer):
self.workerThreads.append(WorkerThread())
self.workerThreads[-1].setGameName(stringer)
self.workerThreads[-1].start()
harro = GG()
harro.startThread("hello")
harro.startThread("hi")