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()
相关推荐
yunson_Liu3 分钟前
编写Python脚本在域名过期10天内将域名信息发送到钉钉
开发语言·python·钉钉
布林模型1 小时前
缠论工具czsc快速使用入门(二)
python·缠论·快速入门·czsc
邂逅you1 小时前
用python操作mysql之pymysql库基本操作
数据库·python·mysql
啊森要自信1 小时前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash
合作小小程序员小小店1 小时前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
渣渣盟2 小时前
解密NLP:从入门到精通
人工智能·python·nlp
老程序员刘飞2 小时前
注册 区块链节点
python
KAIWEILIUCC2 小时前
Python抽象基类(abc.ABC)介绍
python
独行soc2 小时前
2025年渗透测试面试题总结-106(题目+回答)
网络·python·安全·web安全·adb·渗透测试·安全狮
千与千寻酱2 小时前
排列与组合在编程中的实现:从数学概念到代码实践
前端·python