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

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

相关推荐
向阳蒲公英3 分钟前
Pycharm2025版本配置Anaconda步骤
python
每天吃饭的羊4 分钟前
媒体查询
开发语言·前端·javascript
Darkershadow9 分钟前
蓝牙学习之uuid与mac
python·学习·ble
北海有初拥12 分钟前
Python基础语法万字详解
java·开发语言·python
阿里嘎多学长24 分钟前
2026-01-02 GitHub 热点项目精选
开发语言·程序员·github·代码托管
天远云服33 分钟前
Go语言高并发实战:集成天远手机号码归属地核验API打造高性能风控中台
大数据·开发语言·后端·golang
Mqh1807621 小时前
day61 经典时序模型3
python
我想吃烤肉肉1 小时前
logger比print优秀之处
python
2501_941877131 小时前
在法兰克福企业级场景中落地零信任安全架构的系统设计与工程实践分享
开发语言·php
Cosmoshhhyyy1 小时前
《Effective Java》解读第32条:谨慎并用泛型和可变参数
java·python