线程的创建步骤
线程的创建步骤
- 导入线程模块
- 通过线程类创建线程对象
- 启动线程执行任务
import threading
线程对象 = threading.Thread(target=任务)
线程对象.start()
通过线程类创建线程对象
线程对象 = threading.Thread(target=任务名)
参数名 | 说明 |
---|---|
target | 执行的目标任务名,这里指的是函数名 |
name | 线程名,一般不用设置 |
group | 线程组,目前只能使用None |
线程创建与启动的代码
import threading
import time
# 编写代码
def coding():
for i in range(3):
print('coding...')
time.sleep(0.2)
# 听音乐
def music():
for i in range(3):
print('music...')
time.sleep(0.2)
if __name__ == '__main__':
# coding()
# music()
# 创建子线程
coding_thread = threading.Thread(target=coding)
music_thread = threading.Thread(target=music)
# 启动子线程
coding_thread.start()
music_thread.start()