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

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

相关推荐
gCode Teacher 格码致知26 分钟前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
t***54429 分钟前
如何在Dev-C++中选择Clang编译器
开发语言·c++
橙子1991101629 分钟前
Java 基础相关
java·开发语言
不要秃头的小孩31 分钟前
力扣刷题——509. 斐波那契数
python·算法·leetcode·动态规划
科雷软件测试37 分钟前
使用python+Midscene.js AI驱动打造企业级WEB自动化解决方案
前端·javascript·python
星越华夏1 小时前
python——三角函数用法
开发语言·python
代码中介商1 小时前
C语言数据存储深度解析:从原码反码补码到浮点数存储
c语言·开发语言·内存
gmaajt2 小时前
mysql如何检查数据库表是否存在损坏_使用CHECK TABLE命令修复
jvm·数据库·python
heRs BART2 小时前
【Flask】四、flask连接并操作数据库
数据库·python·flask