2015-05-14 102 views
1
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() 

我不確定我是否正確,如果我不是,請更正我。我期待輸出按這個順序打印你好,你好,你好。因爲我期望創建的兩個線程並行運行。但我得到了下面的輸出,你好你好2和嗨。線程2僅在完成thread1之後運行。我做錯了什麼?或者我的理解或線程錯誤?python中的多線程不按預期工作

+0

您正在調用函數並將其結果直接傳遞給Thread()的構造函數。 –

回答

3

你需要傳遞一個函數參考Thread()類的構造函數,這需要「關鍵字參數」叫target默認:None)。

傳遞一個函數調用的結果(比如你做了什麼)將有意外的行爲,特別是因爲第一個參數Thread()實際上group=None是。

實施例:校正

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={})

此構造應始終關鍵字參數調用。