import threading
import time
def test1():
print "hello"
time.sleep(15)
print "hello2"
def test2():
print "hi"
th1 =threading.Thread(test1())
th2 =threading.Thread(test2())
p=[th1,th2]
for i in p:
i.start()
for i in p:
i.join()
不知道我说得对不对,如果不对请指正。我希望输出按照 hello hi 和 hello2 的顺序打印。因为我期望创建的两个线程并行运行。但我得到以下输出,hello hello2 和 hi。线程 2 仅在线程 1 完成后才运行。我做错了什么吗?还是我的理解或线程错误?
最佳答案
您需要将函数引用传递给 Thread()
类构造函数,该构造函数采用名为 target
的“关键字参数”(默认值:None
)。
传递函数调用的结果(例如您所做的)将会产生不良行为,特别是因为 Thread()
的第一个参数实际上是 组=无
。
示例:(已更正)
import threading
import time
def test1():
print "hello"
time.sleep(15)
print "hello2"
def test2():
print "hi"
th1 = threading.Thread(target=test1)
th2 = threading.Thread(target=test2)
p = [th1, th2]
for i in p:
i.start()
for i in p:
i.join()
输出:
$ python foo.py
hello
hi
# 15s delay
hello2
具体:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
This constructor should always be called with keyword arguments.
关于python - python 中的多线程未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229706/