2015-05-14 38 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={})

此构造应始终关键字参数调用。