继承 threading.Thread 类不起作用

6

我是一个多线程的新手,所以答案可能非常简单。

我正在尝试创建一个类的两个实例并让它们并行运行。我已经阅读到可以使用类继承来实现这一点。

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之间的数字)

你能解释一下我做错了什么吗?
这个继承是为了做其他事情而设计的吗?

编辑:我想并行运行这两个对象,所以由于第二个对象等待时间更短,它必须更早地打印出这些数字。

根据porglezomps评论,我尝试更改代码 - 添加一个打印这些数字的方法,但它会按顺序打印。问题仍然存在。


我不明白你认为你在这里使用了类继承的方式(除了类从Thread继承这一微不足道的意义)。然而,你没有提到问题所在;你的输出与你期望的有何不同? - Daniel Roseman
1
你正在构造函数中完成所有工作,但构造函数在主线程上运行。 - porglezomp
@porglezomp 好的,我尝试创建了一个打印类方法,但问题仍然存在。class hello(threading.Thread): def init(self,min,max): threading.Thread.init(self) self.min = min self.max = maxdef print_it(self): time.sleep(self.max) for i in range(20): print random.choice(range(self.min,self.max)) - Milano
2个回答

24

线程的文档说明,您应该覆盖run()方法,然后使用start()方法在新线程上开始执行。在您的情况下,您的代码应该是:

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()

3
根据Python线程文档,您必须在对线程进行任何其他操作之前调用基类构造函数(Thread.init())。 - Ken Block
1
这是@KenBlock提到的声明链接:https://docs.python.org/3/library/threading.html#threading.Thread。 - pfabri

2

Python的常规线程实现已经知道如何运行任务,因此除非您正在创建一种特殊类型的线程(而不是特殊类型的任务)-您可能想要使用常规线程:

def task(_min, _max): # 'min' and 'max' are actual functions!
    time.sleep(_max)
    for _ in range(1000):
        print random.choice(range(_min,_max))

现在创建一个线程来运行任务:

t1 = threading.Thread(target=task, args=(3, 5,))
t2 = threading.Thread(target=task, args=(3, 5,))

t1.start()
t2.start()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接