线程(五):将建立线程的threading.Thread进行重写,更适合工作

# coding:utf-8

'''
 工作当中面向对象重写 threading.Thread
 重写实际上是对threading.Thread的run方法的重写
 run在默认情况下不会执行任何动作,但是当我们调用线程的start方法的
 时候,会执行run的功能
 run就是python预留给大家用来重写多线程的功能,我们重写run来定义
 新功能

'''

# import threading
# import time
#
# class MyThread(threading.Thread):
#
#     def __init__(self):
#         threading.Thread.__init__(self)#重写__init__方法的时候保留了以前的__init__方法
#     def run(self):
#         print("this is our thread it is start",time.ctime())
#         time.sleep(2)
#         print("this is our thread it is done",time.ctime())
#
# thread_list = []
#
# for i in range(10):
#     m = MyThread()
#     thread_list.append(m)
# for i in thread_list:
#     i.start()
# for i in thread_list:
#     i.join()

#以下是改进的重写
import threading
import time

class MyThread(threading.Thread):
    def __init__(self,name,age,nsec):
        threading.Thread.__init__(self)
        self.name = name
        self.age = age
        self.nsec = nsec
    def run(self):
        print("%s is %s"%(self.name,self.age))
        time.sleep(self.nsec)

userData = {
    "name":["a","b","c","d","e"],
    "age":[18,15,19,17,16],
    "nsec":[2,1,3,2,4]
    }

thread_list=[]
length = len(userData['name'])  #获取多少人
name_list = userData['name']
age_list = userData['age']
nsec_list = userData['nsec']

for i in range(length):
    m = MyThread(name_list[i],age_list[i],nsec_list[i])
    thread_list.append(m)
for i in thread_list:
    i.start()
for i in thread_list:
    i.join()

猜你喜欢

转载自blog.csdn.net/a_lazy_zhu/article/details/80193022
今日推荐