Python并发编程—自定义线程类
2020-12-06 23:04
                         标签:splay   python   join   回收   play   closed   ide   threading   join()    1.创建步骤 2.使用方法   Python并发编程—自定义线程类 标签:splay   python   join   回收   play   closed   ide   threading   join()    原文地址:https://www.cnblogs.com/maplethefox/p/10989201.html自定义线程类
【1】 继承Thread类
【2】 重写__init__方法添加自己的属性,使用super加载父类属性
【3】 重写run方法
【1】 实例化对象
【2】 调用start自动执行run方法
【3】 调用join回收线程

 1 from threading import Thread
 2 from time import sleep, ctime
 3 
 4 
 5 class MyThread(Thread):
 6   def __init__(self, target=None,args=(), kwargs={}):
 7     super().__init__()
 8     self.target = target
 9     self.args = args
10     self.kwargs = kwargs
11 
12   def run(self):
13     self.target(*self.args, **self.kwargs)
14 
15 
16 def player(sec, song):
17   for i in range(3):
18     print("Playing %s : %s" % (song, ctime()))
19     sleep(sec)
20 
21 
22 t = MyThread(target=player, args=(3,),
23              kwargs={‘song‘: ‘凉凉‘})
24 t.start()
25 t.join()