python_day17_多线程

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()

元组中仅含一个元素时,需加逗号,多线程传参

相关推荐
小成2023032026511 小时前
Linux高级02
linux·开发语言
知行合一。。。11 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y11 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
咸鱼2.012 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H12 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐12 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子12 小时前
Java:异常(exception)
java·开发语言
lifewange12 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
pluvium2712 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
cmpxr_12 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法