网络编程-线程-3、通过继承Thread类创建线程

知识点:之前第一节介绍创建线程的方法是:通过threading.Thread(target=函数名不要加括号)创建一个对象,通过对象调用start方法创建并启动线程;

                                                                      这一节介绍另外一种创建线程的方法:写一个子类,继承Thread类,里面定义一个run方法即可通过该子类创建一个线程

 

代码如下,解释看注解:

 

#!/usr/bin/env python
# coding=utf-8
# author:刘仲
# datetime:2018/7/23 9:57
# software: PyCharm
import threading
import time

# 通过继承Thred类创建线程

# 线程1
class Mythread(threading.Thread):
    def run(self):  # 类里面必须定义一个run方法,当调用start方法时,会自动运行run方法,run里面的代码就是要执行的子线程
        self.test1()

    def test1(self):
        for i in range(3):
            print('我是线程1')
            time.sleep(1)

# 线程2
class Mythread1(threading.Thread):
        def run(self):
            self.test2()
            
        def test2(self):
            for i in range(3):
                print('我是线程2')
                time.sleep(1)


if __name__ == '__main__':
    t = Mythread()
    t1 = Mythread1()
    t.start()
    t1.start()

 

posted @ 2018-07-23 11:41  上海小盖伦  阅读(190)  评论(0编辑  收藏  举报