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

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

相关推荐
千寻girling3 分钟前
面试官 : “ 说一下 Python 中的常用的 字符串和数组 的 方法有哪些 ? ”
人工智能·后端·python
森林里的程序猿猿5 分钟前
并发设计模式
java·开发语言·jvm
222you14 分钟前
四个主要的函数式接口
java·开发语言
第一程序员21 分钟前
Python基础学习路径:非科班转码者的入门指南
python·github
u01368638236 分钟前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
smchaopiao1 小时前
Python中字典与列表合并的问题与解决方法
开发语言·python
卡尔特斯2 小时前
Ultralytics YOLO26 自动对指定标注文件夹区分标注素材脚本与训练脚本
python·openai
敲代码的瓦龙2 小时前
Java?面向对象三大特性!!!
java·开发语言
2501_921649492 小时前
期货 Tick 级数据与基金净值历史数据 API 接口详解
开发语言·后端·python·websocket·金融·区块链