源代码如下:
#!/usr/bin/env python
import threading
from time import sleep,ctime
loops = [4,2]
def loop(nloop,nsec):
print('start loop',nloop,'at:',ctime())
sleep(nsec)
print('loop',nloop,'done at:',ctime())
def main():
print('starting at:',ctime())
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop,
args=(i,loops[i]))
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print('all DONE at:',ctime())
if __name__ == '__main__':
main()
运行结果:
starting at: Sat Feb 2 22:40:50 2019
start loopstart loop 01 at:at: Sat Feb 2 22:40:50 2019
Sat Feb 2 22:40:50 2019
loop 1 done at: Sat Feb 2 22:40:52 2019
loop 0 done at: Sat Feb 2 22:40:54 2019
all DONE at: Sat Feb 2 22:40:54 2019
为什么不是:
starting at: Sat Feb 2 22:40:50 2019
start loop 0 at: Sat Feb 2 22:40:50 2019
start loop 1 at: Sat Feb 2 22:40:50 2019
loop 1 done at: Sat Feb 2 22:40:52 2019
loop 0 done at: Sat Feb 2 22:40:54 2019
all DONE at: Sat Feb 2 22:40:54 2019