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

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

相关推荐
天若有情673几秒前
【Python】什么是列表推导式?
开发语言·python
xyd陈宇阳11 分钟前
C++ 入门三:函数与模板
开发语言·c++
星之卡比*11 分钟前
前端知识点---闭包(javascript)
开发语言·前端·javascript
oioihoii33 分钟前
C++23新特性详解:迈向更现代化的C++
开发语言·c++·c++23
JoshuaGraham1 小时前
Java 并发-newFixedThreadPool
java·开发语言
Bruce_Liuxiaowei1 小时前
基于Flask的勒索病毒应急响应平台架构设计与实践
后端·python·flask
iFlyCai1 小时前
Xcode警报“Ignoring duplicate libraries: ‘-lc++’” 警报
开发语言·c++
Channing Lewis1 小时前
python headq包介绍
python
Freak嵌入式1 小时前
一文速通 Python 并行计算:06 Python 多线程编程-基于队列进行通信
开发语言·python·多线程·面向对象·并行计算
无名之逆1 小时前
[特殊字符] 超轻高性能的 Rust HTTP 服务器 —— Hyperlane [特殊字符][特殊字符]
java·服务器·开发语言·前端·网络·http·rust