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()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM