python笔记8-多线程threading之封装式

执行函数

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("结束线程: " + self.name)

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("结束线程: " + self.name)


# 创建新线程
thread1 = myThread("海海", "线程A")
thread2 = myThread("老王", "线程B")


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

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

 



posted @ 2018-03-21 15:20  隔壁的王先森  阅读(541)  评论(0编辑  收藏  举报