我正在阅读教程来了解多线程,并且到处都看到人们重写 run 方法。我不清楚from the doc
This class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the init() and run() methods of this class.
Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.**
那么如何创建一个界面,让用户可以在自己的单独线程中选择 doX
或 doY
呢?例如,如果需要运行,我是否必须做这样的事情?
class MyCls(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def doX(self):
while True:
time.slee(10)
return 'x'
def doY(self):
while True:
time.slee(10)
return 'y'
def run(self, dowhat):
assert dowhat.lower() in 'xy', "Can only do X or Y"
return getattr(self,'do'+dowhat.upper())()
用法:
o1 = MyCls()
o1.start()
o1.run('x')
#separate thread
o2 = MyCls()
o2.start()
o2.run('y')
是否有任何方法可以方便地执行 o1.doX()
,从而在自己的线程中执行 doX() ?
最佳答案
在这种情况下,您甚至不需要子类化线程。简单
from threading import Thread
class Thingy(object):
@staticmethod
def doX():
print ("X")
@staticmethod
def doY():
print ("Y")
worker1 = Thread(target=Thingy.doX).start()
worker2 = Thread(target=Thingy.doY).start()
编辑: 我想你的意思是像生成器这样的东西每次都在线程中计算?这或多或少是你想要的吗?
from threading import Thread
import time
class Thingy(object):
def doX(self, rng):
for i in range(0, rng):
worker1 = Thread(target=self.doY)
worker1.start()
worker1.join()
yield self.item
def doY(self):
self.item = time.time()
gen = Thingy().doX(5)
print (gen.next(), str(type(gen)))
print (list(gen))
结果
(1416756265.972083, "<type 'generator'>")
[1416756265.972913, 1416756265.973542, 1416756265.974052, 1416756265.974545]
关于python线程模块: Is overriding run() necessary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088797/