python threading join

encoding=utf-8

from time import sleep,ctime
import threading

loops = [6,2]

def loop(nloop,nsec):
print “loop “,nloop,” start at:”,ctime()
sleep(nsec)
print “loop “,nloop,” runing at:”,ctime()
sleep(nsec)
print “loop “,nloop,” end at:”,ctime()

def main():
print “main start at:”,ctime()
threads = []
nloops = len(loops)

i = 0
while i < nloops:
    t = threading.Thread(target=loop,args=(i,loops[i]))
    threads.append(t)
    i = i + 1

# 一个一个的启动
for item in threads:
    item.start()

# 允许主线程等待线程的结束
# 如果没有join就不会等待所有的线程完成
for item in threads:
    item.join()

print "all end at:",ctime()

if name == ‘main‘:
main()

运行结果:
main start at: Thu Jan 21 09:40:23 2016
loop 0 start at: Thu Jan 21 09:40:23 2016
loop 1 start at: Thu Jan 21 09:40:23 2016
loop 1 runing at: Thu Jan 21 09:40:25 2016
loop 1 end at: Thu Jan 21 09:40:27 2016
loop 0 runing at: Thu Jan 21 09:40:29 2016
loop 0 end at: Thu Jan 21 09:40:35 2016
all end at: Thu Jan 21 09:40:35 2016

你可能感兴趣的:(python)