python 多任务
多线程
python的thread模块是⽐较底层的模块,python的threading
模块是对thread做了⼀些包装的,可以更加⽅便的被使⽤
调用
1 直接调用
# –*– coding: utf-8 –*–
# @Time : 2019/1/7 22:21
# @Author : Damon_duanlei
# @FileName : thread_test01.py
# @BlogsAddr : https://blog.youkuaiyun.com/Damon_duanlei
import threading
import time
def hello_bye(name):
print("hello! {}".format(name))
time.sleep(1)
print("bye! {}".format(name))
if __name__ == '__main__':
t1 = threading.Thread(target=hello_bye, args=("臭臭",))
t2 = threading.Thread(target=hello_bye, args=("小迪",))
t1.start()
t2.start()
运行结果:
>>>
hello! 臭臭
hello! 小迪
bye! 臭臭
bye! 小迪
2 继承 Threading.Thread
# –*– coding: utf-8 –*–
# @Time : 2019/1/7 22:29
# @Author : Damon_duanlei
# @FileName : thread_test02.py
# @BlogsAddr : https://blog.youkuaiyun.com/Damon_duanlei
import threading
import time
def hello_bye(name):
print("hello! {}".format(name))
time.sleep(1)
print("bye! {}".format(name))
class MyThread(threading.Thread):
def __init__(self, func, name):
threading.Thread.__init__(self)
self.func = func
self.name = name
def run(self):
self.func(self.name)
if __name__ == '__main__':
t1 = MyThread(hello_bye, "臭臭")
t2 = MyThread(hello_bye, "小迪")
t1.start()
t2.start()
运行结果:
>>>
hello! 臭臭
hello! 小迪
bye! 臭臭
bye! 小迪
区别
使用继承的方式重写run()方法,start()时不走父类的run()方法,而是走子类重写的run()方法.使用threading.Thread直接创建,start()的时候走Thread类下的run()方法,该run()方法会主动调用 target 函数. 所以使用继承方式调用多线程需要将业务逻辑写入重写后的run()方法.
线程的执行顺序
# –*– coding: utf-8 –*–
# @Time : 2019/1/13 11:07
# @Author : Damon_duanlei
# @FileName : thread_runing_order.py
# @BlogsAddr : https://blog.youkuaiyun.com/Damon_duanlei
import threading
import time
class