32.多线程线程

线程之间内存是共享的。

使用threading模块实现多线程编程。

import threading

thread_obj = threading.Thread([group [, target [, name[, args [, keyargs]]]]] )

  • group: 暂时无用,未来功能的预留参数

  • target: 执行的目标任务名,就是函数的名称

  • name: 线程名,一般不用设置

  • args: 以元组的方式给执行任务传参

  • kwargs: 以字典的方式给执行任务传参

启动线程,让线程开始工作

thread_obj.start()

python 复制代码
import time
import threading


def sing():
    while True:
        print("我在唱歌,啦啦啦")
        time.sleep(1)


def dance():
    while True:
        print("我在跳舞,哗哗哗")
        time.sleep(1)


thread1 = threading.Thread(target=sing)
thread2 = threading.Thread(target=dance)
thread1.start()
thread2.start()

给线程传参args

python 复制代码
import time
import threading


def sing(msg):
    while True:
        print(msg)
        time.sleep(1)


def dance(msg):
    while True:
        print(msg)
        time.sleep(1)


thread1 = threading.Thread(target=sing, args=('我在唱歌...',))
thread2 = threading.Thread(target=dance, args=("我在跳舞...",))
thread1.start()
thread2.start()

给线程传参kwargs

python 复制代码
import time
import threading


def sing(msg):
    while True:
        print(msg)
        time.sleep(1)


def dance(msg):
    while True:
        print(msg)
        time.sleep(1)


thread1 = threading.Thread(target=sing, kwargs={'msg': '我在唱歌'})
thread2 = threading.Thread(target=dance, kwargs={'msg': '我在跳舞'})
thread1.start()
thread2.start()
相关推荐
yvestine40 分钟前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示
zzc9211 小时前
MATLAB仿真生成无线通信网络拓扑推理数据集
开发语言·网络·数据库·人工智能·python·深度学习·matlab
编程有点难1 小时前
Python训练打卡Day43
开发语言·python·深度学习
2301_805054561 小时前
Python训练营打卡Day48(2025.6.8)
pytorch·python·深度学习
LjQ20401 小时前
网络爬虫一课一得
开发语言·数据库·python·网络爬虫
哆啦A梦的口袋呀2 小时前
基于Python学习《Head First设计模式》第九章 迭代器和组合模式
python·学习·设计模式
sponge'2 小时前
opencv学习笔记2:卷积、均值滤波、中值滤波
笔记·python·opencv·学习
databook3 小时前
概率图模型:机器学习的结构化概率之道
python·机器学习·scikit-learn
拾回程序猿的圈圈∞3 小时前
实战二:开发网页端界面完成黑白视频转为彩色视频
python·ai编程
亚林瓜子3 小时前
AWS Elastic Beanstalk + CodePipeline(Python Flask Web的国区CI/CD)
python·ci/cd·flask·web·aws·beanstalk·codepipeline