经过总结,Python创建多线程主要有如下两种方法:
- 函数
- 类
接下来,我们就来揭开多线程的神秘面纱。
学会使用函数创建多线程
在Python3中,Python提供了一个内置模块 threading.Thread
,可以很方便地让我们创建多线程。
threading.Thread()
一般接收两个参数:
- 线程函数名:要放置线程让其后台执行的函数,由我们自已定义,注意不要加
()
; - 线程函数的参数:线程函数名所需的参数,以元组的形式传入。若不需要参数,可以不指定。
举个例子
import time
from threading import Thread
# 自定义线程函数。
def main(name="Python"):
for i in range(2):
print("hello", name)
time.sleep(1)
# 创建线程01,不指定参数
thread_01 = Thread(target=main)
# 启动线程01
thread_01.start()
# 创建线程02,指定参数,注意逗号
thread_02 = Thread(target=main, args=("MING",))
# 启动线程02
thread_02.start()
可以看到输出
1hello Python
2hello MING
3hello Python
4hello MING
是不是超级简单呢?别急,下面也是一样简单。
学会使用类创建多线程
相比较函数而言,使用类创建线程,会比较麻烦一点。
首先,我们要自定义一个类,对于这个类有两点要求,
- 必须继承
threading.Thread
这个父类; - 必须覆写
run
方法。
这里的 run
方法,和我们上面线程函数
的性质是一样的,可以写我们的业务逻辑程序。在 start()
后将会调用。
来看一下例子
为了方便对比,run
函数我复用上面的main
。
import time
from threading import Thread
class MyThread(Thread):
def __init__(self, name="Python"):
# 注意,super().__init__() 一定要写
# 而且要写在最前面,否则会报错。
super().__init__()
self.name=name
def run(self):
for i in range(2):
print("hello", self.name)
time.sleep(1)
if __name__ == '__main__':
# 创建线程01,不指定参数
thread_01 = MyThread()
# 创建线程02,指定参数
thread_02 = MyThread("MING")
thread_01.start()
thread_02.start()
当然结果也是一样的。
1hello Python
2hello MING
3hello Python
4hello MING
多线程:必学函数讲解
学完了两种创建线程的方式,你一定会惊叹,咋么这么简单,一点难度都没有。
其实不然,上面我们的线程函数
为了方便理解,都使用的最简单的代码逻辑。而在实际使用当中,多线程运行期间,还会出现诸多问题,只是我们现在还没体会到它的复杂而已。
不过,你也不必担心,在后面的章节中,我会带着大家一起来探讨一下,都有哪些难题,应该如何解决。
磨刀不误吹柴工,我们首先得来认识一下,Python给我们提供的 Thread
都有哪些函数和属性,实现哪些功能。学习完这些,在后期的学习中,我们才能更加得以应手。
经过我的总结,大约常用的方法有如下这些:
t=Thread(target=func)
# 启动子线程
t.start()
# 阻塞子线程,待子线程结束后,再往下执行
t.join()
# 判断线程是否在执行状态,在执行返回True,否则返回False
t.is_alive()
t.isAlive()
# 设置线程是否随主线程退出而退出,默认为False
t.daemon = True
t.daemon = False
# 设置线程名
t.name = "My-Thread"
好了,Python线程基础知识,我们大概都介绍完了。