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

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

相关推荐
c骑着乌龟追兔子几秒前
Day 38 官方文档的阅读
python
JIngJaneIL12 分钟前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
羸弱的穷酸书生22 分钟前
国网 i1协议 python实现
开发语言·python
weixin_4620223523 分钟前
RAW-Adapter: Adapting Pre-trained Visual Model to Camera RAW Images
python·计算机视觉
电子硬件笔记24 分钟前
Python语言编程导论第三章 编写程序
开发语言·python·编辑器
布谷歌24 分钟前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#
cooldream200929 分钟前
当代 C++ 的三大技术支柱:资源管理、泛型编程与模块化体系的成熟演进
开发语言·c++
洲星河ZXH1 小时前
Java,集合框架体系
开发语言·windows
宠..1 小时前
写一个感染型病毒
开发语言·安全·安全性测试
wheelmouse77881 小时前
一个优雅、通用、零侵入的 CSV 导出工具类(Java 实战)
java·开发语言