# 线程: 线程可以理解成执行代码的分支, 线程是执行对应的代码的, cpu调度线程去执行对应代码 import time import threading # 跳舞的任务 def dance(): # 获取当前执行代码的线程 current_thread = threading.current_thread() print("dance:", current_thread) for i in range(5): print("跳舞中....") time.sleep(0.2) # 唱歌 def sing(): # 获取当前执行代码的线程 current_thread = threading.current_thread() print("sing:", current_thread) for i in range(5): print("唱歌中....") time.sleep(0.2) if __name__ == '__main__': # 获取当前执行代码的线程 current_thread = threading.current_thread() print("main:", current_thread) # 获取程序活动线程的列表 thread_list = threading.enumerate() #print("111:", thread_list) # 创建跳舞的线程 dance_thread = threading.Thread(target=dance) #print("dance_thread:", dance_thread) # 创建唱歌的线程 sing_thread = threading.Thread(target=sing) #print("sing_thread:", sing_thread) thread_list = threading.enumerate() #print("222:", thread_list) # 启动线程执行对应的任务 dance_thread.start() sing_thread.start() # 提示:线程执行完成任务以后该线程就会销毁 thread_list = threading.enumerate() #print("333:", thread_list, len(thread_list)) # 扩展-获取活动线程的个数 active_count = threading.active_count() # print("333:", active_count) # # 主线程执行唱歌 # sing() # 注意点: 线程之间执行是无序的,由cpu调度决定的