0

我正在为我正在从事的项目尝试线程。这是我用作测试的代码

import threading


class one(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        while 1:
            print "one"


class two(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        while 1:
            print "two"

threads = []

one = one()
two = two()

one.start()
two.start()


threads.append(one)
threads.append(two)

for t in threads:
    t.join()

问题是只有第一类运行。你能看出我的代码有问题吗?

4

2 回答 2

4

您必须覆盖该run方法,而不是__init__

class one(threading.Thread):
    def run(self):
        while 1:
            print "one"

此方法在不同的线程上执行,而one = one()在创建对象的同一线程中启动无限循环。

__init__如果要传递要在新线程中使用的参数,请覆盖,例如:

class NumberedThread(threading.Thread):
    def __init__(self, number):
        threading.Thread.__init__(self)
        self.number = number

    def run(self):
        while 1:
            print self.number

NumberedThread("one").start()
NumberedThread("two").start()
于 2013-06-05T20:39:16.127 回答
1

您在线程构造函数中放置了一个无限循环。你的第一个“线程”甚至永远不会离开它的构造函数,所以试图创建它的代码只是坐下来等待对象被创建。结果,您实际上并没有对任何东西进行多线程处理:您只是在主线程中有一个无限循环。

覆盖run而不是,__init__你应该已经准备好了。

class one(threading.Thread):
    def run(self):
        while 1:
            print "one"


class two(threading.Thread):
    def run(self):
        while 1:
            print "two"
于 2013-06-05T20:39:49.407 回答