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

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

相关推荐
查古穆14 分钟前
python进阶-Pydantic模型
开发语言·python
沐知全栈开发16 分钟前
Bootstrap4 导航栏
开发语言
kyriewen1119 分钟前
异步编程:从“回调地狱”到“async/await”的救赎之路
开发语言·前端·javascript·chrome·typescript·ecmascript·html5
AI+程序员在路上22 分钟前
嵌入式软件技术大全
linux·开发语言·arm开发·单片机
吴声子夜歌23 分钟前
JavaScript——数据类型
开发语言·javascript·ecmascript
佳木逢钺30 分钟前
PyQt界面美化系统高级工具库:打造现代化桌面应用的完整指南
python·pyqt
2401_8796938743 分钟前
C++中的观察者模式实战
开发语言·c++·算法
工頁光軍1 小时前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn1 小时前
特殊方法与运算符重载
python
wregjru1 小时前
【网络】8.五种 I/O 模型与多路转接详解
开发语言·php