python笔记8-多线程threading之封装式 执行函数 重写threading.Thread start和run区别 参考代码

前言

冬天到了,小伙伴们最喜欢和好朋友一起吃火锅了,那么这种多个人同时吃火锅的场景如何用python实现呢?

1.先写一个执行函数,用来实现做某件事情,不同的人吃火锅用一个参数people代替。

# coding=utf-8
import threading
import time

def chiHuoGuo(people):
    print("%s 吃火锅的小伙伴-羊肉:%s" % (time.ctime(),people))
    time.sleep(1)
    print("%s 吃火锅的小伙伴-鱼丸:%s" % (time.ctime(),people))

重写threading.Thread

1.使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法

# coding=utf-8
import threading
import time

class myThread (threading.Thread):   # 继承父类threading.Thread
    def __init__(self, people, name):
        '''重写threading.Thread初始化内容'''
        threading.Thread.__init__(self)
        self.threadName = name
        self.people = people

    def run(self):   # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        '''重写run方法'''
        print("开始线程: " + self.threadName)

        chiHuoGuo(self.people)     # 执行任务
        print("qq交流群:226296743")
        print("结束线程: " + self.name)

python笔记8-多线程threading之封装式
执行函数
重写threading.Thread
start和run区别
参考代码

start和run区别

1.start()方法 开始线程活动。

对每一个线程对象来说它只能被调用一次,它安排对象在一个另外的单独线程中调用run()方法(而非当前所处线程)。

当该方法在同一个线程对象中被调用超过一次时,会引入RuntimeError(运行时错误)。

2.run()方法 代表了线程活动的方法。

你可以在子类中重写此方法。标准run()方法调用了传递给对象的构造函数的可调对象作为目标参数,如果有这样的参数的话,顺序和关键字参数分别从args和kargs取得

参考代码

# coding=utf-8
import threading
import time

def chiHuoGuo(people):
    print("%s 吃火锅的小伙伴-羊肉:%s" % (time.ctime(),people))
    time.sleep(1)
    print("%s 吃火锅的小伙伴-鱼丸:%s" % (time.ctime(),people))


class myThread (threading.Thread):   # 继承父类threading.Thread
    def __init__(self, people, name):
        '''重写threading.Thread初始化内容'''
        threading.Thread.__init__(self)
        self.threadName = name
        self.people = people

    def run(self):   # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        '''重写run方法'''
        print("开始线程: " + self.threadName)

        chiHuoGuo(self.people)     # 执行任务
        print("qq交流群:226296743")
        print("结束线程: " + self.name)


# 创建新线程
thread1 = myThread("xiaoming", "Thread-1")
thread2 = myThread("xiaowang", "Thread-2")


# 开启线程
thread1.start()
thread2.start()

time.sleep(0.5)
print("退出主线程")

运行结果:

开始线程: Thread-1
Wed Jan 17 16:33:44 2018 吃火锅的小伙伴-羊肉:xiaoming
开始线程: Thread-2
Wed Jan 17 16:33:44 2018 吃火锅的小伙伴-羊肉:xiaowang
退出主线程
Wed Jan 17 16:33:45 2018 吃火锅的小伙伴-鱼丸:xiaomingWed Jan 17 16:33:45 2018 吃火锅的小伙伴-鱼丸:xiaowang

qq交流群:226296743qq交流群:226296743

结束线程: Thread-1结束线程: Thread-2

备注:这里运行结果会有个问题,主线程已经退出了,子线程Thread-1和Thread-2还在跑。这就是后面需要讲的守护线程了。。。

python自动化交流 QQ群:779429633