python多執行緒實現同時執行兩個while迴圈的操作
阿新 • • 發佈:2020-05-04
如果想同時執行兩個while True迴圈,可以使用多執行緒threading來實現。
完整程式碼
#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)) #建立執行緒 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迴圈中遍歷兩個列表
利用python自帶的zip函式可同時對兩個列表進行遍歷,程式碼如下:
>>> 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多執行緒實現同時執行兩個while迴圈的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。