2016-06-07 70 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