1. 程式人生 > >執行緒(五):將建立執行緒的threading.Thread進行重寫,更適合工作

執行緒(五):將建立執行緒的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()