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

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

相关推荐
shix .2 分钟前
旅行网站控制台检测
开发语言·前端·javascript
小付同学呀5 分钟前
C语言学习(四)——C语言变量、常量
c语言·开发语言
梦游钓鱼20 分钟前
C++指针深度解析:核心概念与工业级实践
开发语言·c++
小雨中_23 分钟前
3.1 RLHF:基于人类反馈的强化学习
人工智能·python·深度学习·算法·动态规划
游乐码29 分钟前
c#索引器
开发语言·c#
jaysee-sjc1 小时前
十三、Java入门进阶:异常、泛型、集合与 Stream 流
java·开发语言·算法
Maggie_ssss_supp1 小时前
Linux-python
开发语言·python
百锦再2 小时前
Java Map常用方法和实现类深度详解
java·开发语言·spring boot·struts·kafka·tomcat·maven
Sunhen_Qiletian2 小时前
回归与分类的本质区别
人工智能·python
星星乘坐的船2 小时前
基于Kubernetes Python SDK实现Job创建
linux·python·kubernetes