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

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

相关推荐
無限進步D13 分钟前
Java 运行原理
java·开发语言·入门
是苏浙15 分钟前
JDK17新增特性
java·开发语言
花酒锄作田2 小时前
企业微信机器人与 DeepAgents 集成实践
python·mcp·deepagents
阿里加多3 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood4 小时前
java中`==`和`.equals()`区别
java·开发语言·python
qq_283720054 小时前
Python Celery + FastAPI + Vue 全栈异步任务实战
vue.js·python·fastapi
2401_885885044 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
zs宝来了5 小时前
AQS详解
java·开发语言·jvm
telllong5 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
wjs20247 小时前
JavaScript 条件语句
开发语言