2016-06-07 35 views
1

我只是玩弄多线程,但我似乎无法得到它的工作。我看过其他问题,但没有一个真正帮助我。这里是我到目前为止的代码:Python 3.4中的多线程如何工作?

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 

回答

1

你想是这样的:

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(target=hello) 
newthread.start() 
otherthread = threading.Thread(target=world) 
otherthread.start() 

# Just for clarity 
newthread.join() 
otherthread.join() 

print("end") 

的联接告诉主线程退出之前在其他线程等待。如果您希望主线程退出而不等待设置demon=True并且不加入。输出结果可能会让你感到惊讶,但并不像你期望的那么干净。例如,我得到这个输出:

HelloWorld 

World 
Hello 
World 
Hello 
WorldHello 
+0

感谢您的回答,完美工作,并且在启动线程之间添加了一小段延迟,以使输出正确。 :) –

2
threading.Thread(hello()) 

您调用的函数hello并通过了结果为Thread,所以它在线程对象存在之前执行。通过普通功能对象:

threading.Thread(target=hello) 

现在Thread将负责执行该功能。

+0

去掉括号后,现在我得到这个错误: newthread = threading.Thread(你好,无) Asse田:组参数必须是无,现在 –

+0

它应该是'threading.Thread(target = hello)' – cdonts

+0

添加'target = hello'作为参数。这告诉它执行该功能。还要为参数添加'args =(arg1,arg2,arg3)'。 – Goodies