threading模块
import timedef sing():while True:print("唱歌~~~~~~~~~~~~")time.sleep(1)def dance():while True:print("跳舞############")time.sleep(1)
if __name__ == '__main__':sing()dance()
此时为单线程
import threading
import timedef sing():while True:print("唱歌~~~~~~~~~~~~")time.sleep(1)def dance():while True:print("跳舞############")time.sleep(1)if __name__ == '__main__':# sing()# dance()# 多线程sing_thread = threading.Thread(target=sing)dance_thread = threading.Thread(target=dance)sing_thread.start()dance_thread.start()
使用threading模块,实现多线程
import threading
import timedef sing_msg(msg):while True:print(msg)time.sleep(1)def dance_msg(msg):while True:print(msg)time.sleep(1)if __name__ == '__main__':# 注意此处元组sing_msg_thread = threading.Thread(target=sing_msg, args=("唱歌",))dance_msg_thread = threading.Thread(target=dance_msg, kwargs={"msg": "跳舞"})sing_msg_thread.start()dance_msg_thread.start()
元组中仅含一个元素时,需加逗号,多线程传参