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

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

相关推荐
似水明俊德1 小时前
02-C#.Net-反射-面试题
开发语言·面试·职场和发展·c#·.net
qq_417695051 小时前
机器学习与人工智能
jvm·数据库·python
漫随流水1 小时前
旅游推荐系统(view.py)
前端·数据库·python·旅游
Thera7772 小时前
C++ 高性能时间轮定时器:从单例设计到 Linux timerfd 深度优化
linux·开发语言·c++
yy我不解释2 小时前
关于comfyui的mmaudio音频生成插件时时间不一致问题(一)
python·ai作画·音视频·comfyui
炘爚3 小时前
C语言(文件操作)
c语言·开发语言
阿蒙Amon3 小时前
C#常用类库-详解SerialPort
开发语言·c#
凸头3 小时前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun3141593 小时前
线程安全需要保证几个基本特征
java·开发语言·jvm
Moksha2623 小时前
5G、VoNR基本概念
开发语言·5g·php