运维辞典@欢迎访问小站,如有疑问,可通过右侧QQ或底部邮箱联系,非常感谢@

自定义多线程方法实现效果

Python Administrator 541℃
from time import sleep, ctime
import threading

class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.func = func
        self.args = args
        self.name = name

    def run(self):
        self.func(*self.args)

def super_player(file_, time):
    for i in range(2):
        print("start playing: %s %s " % (file_, ctime()))
        sleep(time)
        print("playing end: %s %s " % (file_, ctime()))

lists = { '爱情买卖.mp3':3, '阿凡达':5, '我和你':4 }
threads = []
files = range(len(lists))

for file_, time in lists.items():
    t = MyThread(super_player, (file_, time))
    threads.append(t)

if __name__ == '__main__':
    print("begin:", ctime())
    for t in files:
        threads[t].start()
    for t in files:
        threads[t].join()
    print("end:", ctime())

执行结果
begin: Thu Aug 16 14:35:12 2018
start playing: 爱情买卖.mp3 Thu Aug 16 14:35:12 2018
start playing: 阿凡达 Thu Aug 16 14:35:12 2018
start playing: 我和你 Thu Aug 16 14:35:12 2018

playing end: 爱情买卖.mp3 Thu Aug 16 14:35:15 2018
start playing: 爱情买卖.mp3 Thu Aug 16 14:35:15 2018
playing end: 我和你 Thu Aug 16 14:35:16 2018
start playing: 我和你 Thu Aug 16 14:35:16 2018
playing end: 阿凡达 Thu Aug 16 14:35:17 2018
start playing: 阿凡达 Thu Aug 16 14:35:17 2018
playing end: 爱情买卖.mp3 Thu Aug 16 14:35:18 2018
playing end: 我和你 Thu Aug 16 14:35:20 2018
playing end: 阿凡达 Thu Aug 16 14:35:22 2018
end: Thu Aug 16 14:35:22 2018
很明显可以看出,上面三个任务是同时执行的,最后只花费了10秒

码字很辛苦,转载请注明来自:《运维辞典 » 自定义多线程方法实现效果

喜欢 (0)