导入threading库、time库,复制下面代码即可运行
import threading
import time
# 线程一:录制视频
def video_record(name):
for i in range(5):
print("录制{}".format(name))
time.sleep(1)
# 线程二:拍摄图片
def picture_shoot():
for i in range(5):
print('拍摄图片 ')
time.sleep(1)
if __name__=='__main__':
name = '视频'
# 注意这里的格式不要错,因为Thread的参数要求是tuple
thread = threading.Thread(target=video_record, args=(name,)) # 实例化线程
thread.start() # 开始运行该线程
picture_shoot()
运行结果:
D:\Python\python.exe D:/PythonWorkSpace/chenbang/test.py
录制视频
拍摄图片
拍摄图片
录制视频
拍摄图片
录制视频
拍摄图片
录制视频
拍摄图片
录制视频
Process finished with exit code 0
应用场景:封装好视频录制函数和图片拍摄函数后,想要一边录制视频一边拍摄图片,则可以使用该方法。
注意事项:在给target赋值目标函数时不要接括号;如果目标函数需要传参,用args来接收,args要求参数是元组类型;
Python:3.10.0