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

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

相关推荐
JavaWeb学起来5 分钟前
Python学习教程(二)字符串
开发语言·python·python基础
归寻太乙9 分钟前
2026年03月27日—Python基础—Python背景知识与环境搭建
开发语言·python
88号技师9 分钟前
2026年3月新锐一区SCI-傅里叶变换优化算法Fourier transform optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
福楠12 分钟前
现代C++ | 右值引用 + std::move + noexcept
linux·c语言·开发语言·c++
独隅12 分钟前
PyTorch 的全面介绍
人工智能·pytorch·python
小陈工13 分钟前
Python后端实战:GraphQL高级应用与性能优化全解析
开发语言·人工智能·后端·python·性能优化·开源·graphql
代码探秘者15 分钟前
【大模型应用】一篇弄懂Skill
数据结构·数据库·python·算法·spring
不会写DN18 分钟前
Go 生态最快 JSON 库 - jsoniter
开发语言·golang·json
左左右右左右摇晃19 分钟前
Java线程池——核心方法解析execute / submit / shutdown
java·开发语言