python多線程實現同時執行兩個while循環


如果想同時執行兩個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()

效果:

image

參考:http://www.cnblogs.com/fnng/p/3691053.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM