python 多线程
多线程流程
- 导入模块
import threading
- 通过线程类型创建线程对象
线程对象 = threading.Thread(target = '待执行函数',name = (线程命名))
- 启动线程执行任务
线程对象.start()
启动线程
创建子线程
sing_thread = threading.Thread(target = sing)
dance_thread = threading.Thread(target = dance)
启动子线程
sing_thread.start()
dance_thread.start()
线程传参
- args 以元组方式传递
# target 线程函数名
# args 以元组的方式传递参数 args只有一个参数的时候,一定在后面加上',' !!!
sing_thread = threading.Thread(target = sing,args = (3,))
sing_thread.start()
- kwargs 以字典方式传递
# target 线程函数名
# kwargs 以字典的方式传递参数
dance_thread = threading.Thread(target = dance,kwargs = {'count': 3})
dance_thread.start()
例:
import threading,time
def sing(num):
for i in range(num):
print('sing')
time.sleep(1)
def dance(num):
for i in range(num):
print('dance')
time.sleep(1)
if __name__ == '__main__':
sing_thread = threading.Thread(target= sing ,args= (3,))
dance_thread = threading.Thread(target = dance,kwargs= {'num': 5})
sing_thread.start()
dance_thread.start()
主线程和子线程的结束顺序
- 默认主线程等待子线程结束
设置主线程结束子线程销毁
- thread 添加 daemon = True
- 或者在启动线程前添加sing_thread.setDaemon(Ture)
sing_thread.Thread(target = sing ,daemon = Ture)
线程之间的执行顺序
- 默认无序
证实线程之间是无序的
# 通过current_thread方法获取线程对象
current_thread = threading.current_thread()
# 通过current_thread对象可以知道相关信息,例如被创建的顺序
print('current_thread')
import threading,time
def sing():
time.sleep(2)
print(threading.current_thread())
if __name__ == '__main__':
for i in range(5):
sing_thread = threading.Thread(target=sing)
sing_thread.start()