python多線程實現(xiàn)同時執(zhí)行兩個while循環(huán)的操作
更新時間:2020年05月02日 10:32:34 作者:zoro_robin
這篇文章主要介紹了python多線程實現(xiàn)同時執(zhí)行兩個while循環(huán)的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
如果想同時執(zhí)行兩個while True循環(huán),可以使用多線程threading來實現(xiàn)。
完整代碼
#coding=gbk from time import sleep, ctime import threading def muisc(func): while True: print 'Start playing: %s! %s' %(func,ctime()) sleep(2) def move(func): while True: print 'Start playing: %s! %s' %(func,ctime()) sleep(5) def player(name): r = name.split('.')[1] if r == 'mp3': muisc(name) else: if r == 'mp4': move(name) else: print 'error: The format is not recognized!' list = ['愛情買賣.mp3','阿凡達.mp4'] threads = [] files = range(len(list)) #創(chuàng)建線程 for i in files: t = threading.Thread(target=player,args=(list[i],)) threads.append(t) if __name__ == '__main__': #啟動線程 for i in files: threads[i].start() for i in files: threads[i].join() #主線程 print 'end:%s' %ctime()
效果:
補充知識:python 如何在一個for循環(huán)中遍歷兩個列表
利用python自帶的zip函數(shù)可同時對兩個列表進行遍歷,代碼如下:
>>> list1 = ['a', 'b', 'c', 'd'] >>> list2 = ['apple', 'boy', 'cat', 'dog'] >>> for x, y in zip(list1, list2): print(x, 'is', y) # 輸出 a is apple b is boy c is cat d is dog
以上這篇python多線程實現(xiàn)同時執(zhí)行兩個while循環(huán)的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
pycharm實現(xiàn)在虛擬環(huán)境中引入別人的項目
這篇文章主要介紹了pycharm實現(xiàn)在虛擬環(huán)境中引入別人的項目,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03python pandas dataframe 行列選擇,切片操作方法
下面小編就為大家分享一篇python pandas dataframe 行列選擇,切片操作方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04