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

補(bǔ)充知識:python 如何在一個for循環(huán)中遍歷兩個列表
利用python自帶的zip函數(shù)可同時對兩個列表進(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 apple b is boy c is cat d is dog
以上這篇python多線程實(shí)現(xiàn)同時執(zhí)行兩個while循環(huán)的操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用jupyter notebook輸出顯示不完全的問題及解決
這篇文章主要介紹了使用jupyter notebook輸出顯示不完全的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
python實(shí)現(xiàn)教務(wù)管理系統(tǒng)
這篇文章主要介紹了python實(shí)現(xiàn)教務(wù)管理系統(tǒng),實(shí)現(xiàn)了管理員、教職工、學(xué)生三種不同身份的操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
python中Switch/Case實(shí)現(xiàn)的示例代碼
本篇文章主要介紹了python中Switch/Case實(shí)現(xiàn)的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
使用python制作游戲下載進(jìn)度條的代碼(程序說明見注釋)
這篇文章主要介紹了用python制作游戲下載進(jìn)度條的代碼(程序說明見注釋),代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
用python實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了用python實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07

