我有一系列以串行和并行方式继承自的类,如果可能,我需要对所有类使用Python线程。下面是一个例子。问题是Build类没有执行run函数,而run函数是Thread类中的一个方法。线程在MyThread类中运行良好。你知道如何让构建类以线程的形式开始吗?你知道吗
from threading import Thread
from random import randint
import time
class Build(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# This run function currently not being executed
for i in range(20):
print('Second series %i in thread' % (i))
time.sleep(1)
class MyThread(Build, Thread):
def __init__(self, val):
''' Constructor. '''
Thread.__init__(self)
Build.__init__(self)
self.val = val
def run(self):
for i in range(1, self.val):
print('Value %d in thread %s' % (i, self.getName()))
# Sleep for random time between 1 ~ 3 second
secondsToSleep = randint(1, 5)
print('%s sleeping fo %d seconds...' % (self.getName(), secondsToSleep))
time.sleep(secondsToSleep)
# Run following code when the program starts
if __name__ == '__main__':
# Declare objects of MyThread class
myThreadOb1 = MyThread(4)
myThreadOb1.setName('Thread 1')
myThreadOb2 = MyThread(4)
myThreadOb2.setName('Thread 2')
# Start running the threads!
myThreadOb1.start()
myThreadOb2.start()
# Wait for the threads to finish...
myThreadOb1.join()
myThreadOb2.join()
print('Main Terminating...')`
仅供参考:实现所需功能的更好方法不是将
threading.Thread
子类化,而是生成类实例Callable
,并将它们传递给Thread
类的构造函数的target
关键字arg。这样做的好处是可以向每个线程实例传递额外的参数。你知道吗使用示例代码。你知道吗
相关问题 更多 >
编程相关推荐