【发布时间】:2016-05-02 05:11:23
【问题描述】:
我有一系列以串行和并行方式继承的类,我需要尽可能对所有类使用 Python 线程。下面是一个例子。问题是 Build 类没有执行它的 run 函数,这是 Thread 类中的一个方法。不过,线程在 MyThread 类中工作正常。知道如何使 Build 类作为线程开始吗?
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...')`
【问题讨论】:
-
似乎有效。我尝试了您的代码并将
MyThread()之一替换为Build(),它正确调用了run()。
标签: python multithreading class