python线程类实例

python原生的线程类实例:

import threading
from time import ctime,sleep

def music(songs,time):
    for i in range(time):
        print("第{}次播放music{}!时间是{}".format(i,songs,ctime()))
        sleep(2)


def moive(moives,time):
    for i in range(time):
        print("第{}次播放movie{}!时间是{}".format(i,moives,ctime()))
        sleep(5)

threads=[]
t1 = threading.Thread(target=music, args=('love',2))
threads.append(t1)

t2 = threading.Thread(target=moive, args=('小大夫',2))
threads.append(t2)


if __name__ =="__main__":
    for th in threads:
        th.start()

    #守护线程
    for t in threads:
        t.join()

    print('all end:{}'.format(ctime()))

封装自定义的线程类

import threading
from time import ctime,sleep

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_play(files, time):
    for i in range(2):
        print("start palying:{}!{}".format(files,ctime()))
        sleep(time)


lists = {"love.mp3":3, "sunshine.mp3":2, "世界这么大":2}

threads = []
files = len(lists)
for file,time in lists.items():
    t = MyThread(super_play, (file, time), super_play.__name__)
    threads.append(t)

if __name__ == "__main__":
    for i in range(files):
        threads[i].start()

    for j in range(files):
        threads[j].join()

    print("all end {}".format(ctime()))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值