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

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

相关推荐
徐凤年lll39 分钟前
python 初学2
开发语言·python
2301_801252221 小时前
Mybatis的添加和修改功能
java·开发语言·mybatis
坚持就完事了1 小时前
解析数据练习(小项目)
python
周周记笔记1 小时前
Pycharm详解:高效Python开发的首选IDE
ide·python·pycharm
行思理1 小时前
IntelliJIdea 创建java spring boot程序
java·开发语言·spring boot
香辣西红柿炒蛋1 小时前
Python企业编码规范
python
散峰而望1 小时前
C语言刷题(一)
c语言·开发语言·编辑器·github·visual studio
CN-Dust1 小时前
【C++】2025CSP-J第二轮真题及解析
开发语言·c++·算法
温柔一只鬼.2 小时前
Java数组
java·开发语言·算法
仟濹2 小时前
「经典图形题」集合 | C/C++
c语言·开发语言·c++