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

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

相关推荐
winfredzhang16 分钟前
从零构建家庭照片管理系统:Django 模块化单体实战,以及我踩到的 4 个真实坑
python·postgresql·django·sqlite·bootsrap
jyOverQ29 分钟前
LangGraph 流式执行详解:stream、astream 与 stream_mode 怎么选?
python·langchain
法哥201240 分钟前
用 C++ 控制 CMW100,到底在干什么?
开发语言·c++
闲猫1 小时前
LangGraph / Capabilities / Stores
python·agent·langgraph
QH139292318801 小时前
NVIDIA H200 H300服务器
运维·服务器·开发语言·网络·信息与通信
pjj198541 小时前
机器学习-NumPy2
人工智能·python·机器学习
OPEN-F1 小时前
Python进阶教程:单元测试与代码质量
开发语言·python·单元测试
阿里嘎多学长1 小时前
2026-08-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
其实防守也摸鱼1 小时前
Codex破局:前端组件秒级生成的技术文章大纲
开发语言·前端·人工智能·学习·安全·web安全
Logintern091 小时前
装饰器和洋葱模式的区分
开发语言·python·架构