線程(五):將建立線程的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()
發佈了14 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章