1 import threading 2 import time 3 4 5 def listen(music): 6 for i in range(2): 7 print(‘Listen ‘ + music + ‘ start:%s‘ % time.ctime()) 8 time.sleep(2) 9 10 11 def watch(movie): 12 for i in range(2): 13 print(‘Watch ‘ + movie + ‘ start:%s‘ % time.ctime()) 14 time.sleep(3) 15 16 17 threads = [] # 创建线程组 18 19 t1 = threading.Thread(target=listen, args=(‘龙卷风‘,)) # 定义、添加线程,target指定函数,args传参 20 threads.append(t1) 21 t2 = threading.Thread(target=watch, args=(‘肖申克的救赎‘,)) 22 23 threads.append(t2) 24 25 if __name__ == ‘__main__‘: 26 for i in threads: 27 i.setDaemon(True) 28 i.start() 29 for i in threads: # join()的作用是为了让程序执行完上面的子线程,再执行下面的主线程,不然主线程和子线程同时执行,子线程还没完成主线程就结束了 30 i.join() 31 print(‘end:%s‘ % time.ctime())
我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。
运行结果:
1 Listen 龙卷风 start:Tue Aug 31 15:39:35 2021 2 Watch 肖申克的救赎 start:Tue Aug 31 15:39:35 2021 3 Listen 龙卷风 start:Tue Aug 31 15:39:37 2021 4 Watch 肖申克的救赎 start:Tue Aug 31 15:39:38 2021 5 end:Tue Aug 31 15:39:41 2021 6 7 Process finished with exit code 0