python用类的方式创建线程---自创建类

用类的方式创建线---自创建类

import threading
import time


class MyThread(threading.Thread):#自建MyThread类继承threading.Thread类
    def __init__(self, num):      #init方法用来拿参数,拿到实例变量
        threading.Thread.__init__(self)
        self.num = num       #它是实例变量,存在对象t1,t2中

    def run(self): #run就是父类的方法的重写
        # 来定义每个线程要运行的函数


        print("running on number:%s" % self.num)

        time.sleep(3)


if __name__ == '__main__':
    t1 = MyThread(1)  #实例化一个类的对象----创建一个线程
    t2 = MyThread(2)
    t1.start()    #python在start方法中内部封装了run方法
    t2.start()

原文地址:https://www.cnblogs.com/dbslinux/p/11249917.html