python多線程實(shí)現(xiàn)同時(shí)執(zhí)行兩個(gè)while循環(huán)的操作
如果想同時(shí)執(zhí)行兩個(gè)while True循環(huán),可以使用多線程threading來(lái)實(shí)現(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’,’阿凡達(dá).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__’: #啟動(dòng)線程 for i in files: threads[i].start() for i in files: threads[i].join() #主線程 print ’end:%s’ %ctime()
效果:

補(bǔ)充知識(shí):python 如何在一個(gè)for循環(huán)中遍歷兩個(gè)列表
利用python自帶的zip函數(shù)可同時(shí)對(duì)兩個(gè)列表進(jìn)行遍歷,代碼如下:
>>> 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多線程實(shí)現(xiàn)同時(shí)執(zhí)行兩個(gè)while循環(huán)的操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 編程語(yǔ)言PHP在Web開發(fā)領(lǐng)域的優(yōu)勢(shì)在哪?3. 什么是python的自省4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)5. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題6. 基于android studio的layout的xml文件的創(chuàng)建方式7. Android如何加載Base64編碼格式圖片8. Springboot Druid 自定義加密數(shù)據(jù)庫(kù)密碼的幾種方案9. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. 圖文詳解vue中proto文件的函數(shù)調(diào)用

網(wǎng)公網(wǎng)安備