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

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

相关推荐
Clarence Liu6 分钟前
Go Context 深度解析:从源码到 RESTful 框架的最佳实践
开发语言·后端·golang
中年程序员一枚9 分钟前
Python防止重复资源的链接mysql方法
开发语言·python·mysql
天宁10 分钟前
pywebview窗口移动解决方案
python
CodeCraft Studio13 分钟前
国产化Word处理组件Spire.DOC教程:使用Python将文件自动化批量附加到 Word文档
python·自动化·word·spire.doc·文档自动化·word文档中添加附件·文档批量处理
果然途游13 分钟前
完整Java后端学习路径
java·开发语言·学习笔记
Mryan200517 分钟前
基于 Nao 机器人的摄像头和声呐结合寻路方式
python·机器人·nao 机器人·naoqi
Salt_072818 分钟前
DAY 37 MLP 神经网络的训练
人工智能·python·深度学习·神经网络·机器学习
东方佑21 分钟前
使用Python实现Word文档与JSON格式双向转换:完整教程与代码解析
python·json·word
l1t21 分钟前
Javascript引擎node bun deno比较
开发语言·javascript·算法·ecmascript·bun·精确覆盖·teris
三斗米26 分钟前
mac系统查看所有安装的Python版本
python