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

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

相关推荐
cxr828几秒前
GPU 加速声场求解器 CUDA Kernel 实现细节 —— 高频超声传播仿真并行计算引擎
人工智能·python·目标跟踪
echome8888 分钟前
JavaScript Promise 与 async/await 实战:5 个高频异步编程场景的优雅解决方案
开发语言·javascript·ecmascript
枫叶林FYL26 分钟前
第10章 符号推理与神经符号AI
pytorch·python·深度学习
xcLeigh30 分钟前
IoTDB Java 原生 API 实战:SessionPool 从入门到精通
java·开发语言·数据库·api·iotdb·sessionpool
杜子不疼.31 分钟前
Java 智能体学习避坑指南:3 个常见误区,新手千万别踩,高效少走弯路
java·开发语言·人工智能·学习
冬天vs不冷31 分钟前
为什么 Java 不让 Lambda 和匿名内部类修改外部变量?final 与等效 final 的真正意义
android·java·开发语言
星河耀银海32 分钟前
JAVA 多线程编程:从基础原理到实战应用
java·开发语言·php
星河耀银海32 分钟前
JAVA IO流:从基础原理到实战应用
java·服务器·开发语言
摸鱼仙人~1 小时前
Math.js 使用教程
开发语言·javascript·ecmascript
nimadan121 小时前
剧本杀app2025推荐,多类型剧本体验与社交互动优势
人工智能·python