python多線程實現(xiàn)同時執(zhí)行兩個while循環(huán)的操作
如果想同時執(zhí)行兩個while True循環(huán),可以使用多線程threading來實現(xiàn)。
完整代碼
#coding=gbkfrom time import sleep, ctime import threadingdef 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 appleb is boyc is catd is dog
以上這篇python多線程實現(xiàn)同時執(zhí)行兩個while循環(huán)的操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. Java 基于UDP協(xié)議實現(xiàn)消息發(fā)送3. python 如何停止一個死循環(huán)的線程4. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值5. php5.6不能擴展redis.so的解決方法6. PHP獲取時間戳等相關(guān)函數(shù)匯總7. 關(guān)于HTML5的img標簽8. Python編寫nmap掃描工具9. python 爬取嗶哩嗶哩up主信息和投稿視頻10. 如何基于python3和Vue實現(xiàn)AES數(shù)據(jù)加密
