# 1. 导入threading模块
import threading
import time
# 跳舞任务函数
def dance():
for i in range(4):
print("跳舞中...")
time.sleep(0.2)
# 唱歌任务函数
def sing():
for i in range(3):
print("唱歌中...")
time.sleep(0.2)
if __name__ == '__main__':
# 2. 创建子线程对象
# group: 表示线程组,目前只能使用None
# target: 表示执行的任务名(函数名或者方发名),不能加小括号
dance_thread = threading.Thread(target=dance)
print(dance_thread, dance_thread.name)
sing_thread = threading.Thread(target=sing, name="sing_thread2")
print(sing_thread, sing_thread.name)
# 3. 启动线程执行对应的任务
dance_thread.start()
sing_thread.start()
执行结果:
<Thread(Thread-1, initial)> Thread-1
<Thread(sing_thread2, initial)> sing_thread2
跳舞中...
唱歌中...
跳舞中...
唱歌中...
跳舞中...
唱歌中...
跳舞中...