threading模块
python
import time
def sing():
while True:
print("唱歌~~~~~~~~~~~~")
time.sleep(1)
def dance():
while True:
print("跳舞############")
time.sleep(1)
if __name__ == '__main__':
sing()
dance()
此时为单线程
python
import threading
import time
def 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模块,实现多线程
python
import threading
import time
def 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()
元组中仅含一个元素时,需加逗号,多线程传参