zoukankan      html  css  js  c++  java
  • 创建线程类threading.py

    import threading
    from time import sleep,ctime
    #创建线程类:
    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(file_,time):
    for i in range(2):
    print("Start playing: %s! %s" %(file_,ctime()))
    sleep(time)

    lists = {"爱情买卖.mp3":3,"阿凡达.mp4":5,"我和你.mp3":4}

    threads = []
    files = range(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 files:
    threads[i].start()
    for i in files:
    threads[i].join()
    print("end:%s" %ctime())

    """
    创建MyThread类,用于继承threading.Thread类。
    __init__类的初始化方法对func、args、name等参数进行初始化。
    在Python2中,apply(func[,args[,kwargs]])函数的作用是当函数参数已经存在于一个元组或字典中时,apply0间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,则任何参数都不会被传递,kwargs是一个包含关键字参数的字典。
    Python3中已经不再支持apply()函数,
    所以将apply(self.func,self.args)
    修改为
    self.func(*self.args)
    最后,线程的创建与启动与前面的例子相同,唯一的区别是创建线程使用的是MyThread类,线程的入参形式也有所改变。
    """
  • 相关阅读:
    作业: 小型购物系统1---按顺序编写
    字典操作学习小结
    字符操作学习笔记小结
    列表,元组等学习笔记小结
    模块及其数据类型小结
    python3学习笔记----基础知识1
    压力山大
    下周一开始上班啦!
    凌晨12点,沉迷学习,无法自拔...
    web前端开发2018年12月找工作总结
  • 原文地址:https://www.cnblogs.com/zhang-da/p/12210542.html
Copyright © 2011-2022 走看看