我们都知道,代码编程不是固定的东西,而是非常灵活的内容,根据不同的内容,我们可以拓展出很多条内容,最终目的还是为了可以实现结果,给大家举例说明其中一个最常用的多线程吧~以及实现的几种方式。
1. 用函数创建多线程
在Python3中,Python提供了一个内置模块 threading.Thread,可以很方便地让我们创建多线程。
举个例子import time
from threading import Thread
# 自定义线程函数。
def target(name="Python"):
for i in range(2):
print("hello", name)
time.sleep(1)
# 创建线程01,不指定参数
thread_01 = Thread(target=target)
# 启动线程01
thread_01.start()
# 创建线程02,指定参数,注意逗号
thread_02 = Thread(target=target, args=("MING",))
# 启动线程02
thread_02.start()
可以看到输出hello Python
hello MING
hello Python
hello MING
2.用类创建多线程
相比较函数而言,使用类创建线程,会比较麻烦一点。
首先,我们要自定义一个类,对于这个类有两点要求,<