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

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

相关推荐
mqiqe5 分钟前
AgentScope Java 2.0 集成 Chat Completions Web:一行依赖让你的 Agent 变身 OpenAI 兼容服务
java·开发语言·前端
qq_5896660515 分钟前
Java微服务介绍及应用
java·开发语言·微服务
圆圆讲门店24 分钟前
实体获客团队|基础概念与核心要点整理
人工智能·python
uoKent26 分钟前
c++中的extern关键字
开发语言·c++
牧杉-惊蛰31 分钟前
将数组对象根据自定义排列
java·开发语言·算法
砚底藏山河43 分钟前
【量化纯GET实战 #04】批量快照:一次 HTTP GET 取多只股票
java·python·金融·eclipse
君顾11 小时前
家校托管互通:从需求分析到系统架构的落地实践
java·开发语言·托管
烂蜻蜓1 小时前
Flask入门教程(九):模板渲染——用Jinja2构建动态页面
后端·python·flask
2601_966871401 小时前
AE影视后期特效-遮罩/调色/抠像/MG动画/3D/Vlog制作(完结)jzit
python
jimy11 小时前
c++隐式移动构造、强制拷贝省略、返回具名局部变量
开发语言·c++