继承threading.Thread类不起作用 [英] Inheritance threading.Thread class does not work
问题描述
我是多线程技术的新手,所以答案可能很简单.
I'm new in multithreading, so the answer is probably very simple.
我正在尝试制作一个类的两个实例并使其并行运行.我已经读到可以使用类继承来做到这一点.
I'm trying to make two instances of one class and run them parallel. I've read that I can use class inheritance to do that.
class hello(threading.Thread):
def __init__(self,min,max):
threading.Thread.__init__(self)
time.sleep(max)
for i in range(1000):
print random.choice(range(min,max))
h = hello(3,5)
k = hello(0,3)
我注意到这是行不通的(第一个输出是3到5之间的数字)
I've noticed that this does not work (the first outputs are numbers between 3 and 5)
您能解释我在做什么错吗?
该继承是否专门用于做其他事情?
Could you explain what am I doing wrong?
Is this inheritance dedicated to do something else?
我想并行运行这两个对象,因此由于第二个对象的等待时间较短,因此必须更快地打印这些数字.
I want to run these two objects parallel so since the second object has smaller wait, it has to print those numbers sooner.
根据porglezomps的评论,我试图更改代码-添加一种打印这些数字但按顺序打印的方法.问题仍然存在.
According to porglezomps comment, I've tried to change the code - add a method which prints those numbers but it prints it sequentially. The problem is still there.
推荐答案
threading的文档表示您应该覆盖run()
方法,然后使用start()
方法开始在新线程上执行.就您而言,您的代码应为:
The documentation for threading says that you should override the run()
method, and then use the start()
method to begin execution on a new thread. In your case, your code should be:
class Hello(threading.Thread):
def __init__(self, min, max):
self.min, self.max = min, max
threading.Thread.__init__(self)
def run(self):
time.sleep(self.max)
for i in range(1000):
print random.choice(range(self.min, self.max))
# This creates the thread objects, but they don't do anything yet
h = Hello(3,5)
k = Hello(0,3)
# This causes each thread to do its work
h.start()
k.start()
这篇关于继承threading.Thread类不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!