Python-继承与重写实现线程

# coding = utf-8
import threading
import time


class MyThread(threading.Thread):
    # 重写run方法,run方法中是该线程要执行的动作
    def run(self):
        for i in range(5):
            time.sleep(1)
            msg = self.name  # name属性中保存的是当前线程的名字
            print(msg)


def main():
    # 创建自定义的线程类对象
    t = MyThread()
    # 调用自定义线程类中的继承自父类的start方法,执行自定义线程类中的run方法
    t.start()


if __name__ == "__main__":
    main()

执行结果:

Thread-1
Thread-1
Thread-1
Thread-1
Thread-1

猜你喜欢

转载自blog.csdn.net/weixin_44151971/article/details/85230271