我只是在玩多线程,但我似乎无法让它工作。我看过其他问题,但没有一个真正对我有帮助。到目前为止,这是我的代码:
import threading, time
def hello():
for i in range(1,5):
time.sleep(1)
print("Hello")
def world():
for i in range(1,5):
time.sleep(1)
print("World")
newthread = threading.Thread(hello())
newthread.daemon = True
newthread.start()
otherthread = threading.Thread(world())
otherthread.daemon = True
otherthread.start()
print("end")
我希望得到类似的东西:
Hello
World
Hello
World
Hello
World
Hello
World
end
但我得到的是:
Hello
Hello
Hello
Hello
World
World
World
World
end
最佳答案
threading.Thread(hello())
您调用了函数 hello
并将结果传递给 Thread
,因此它在线程对象存在之前就执行了。传递普通函数对象:
threading.Thread(target=hello)
现在线程
将负责执行该函数。
关于python - Python 3.4 中多线程如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37689138/