您的位置:首页 > 编程语言 > Python开发

python threading join

2016-01-21 09:58 513 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: