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()
相关推荐
a1117763 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得03 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
摘星编程6 小时前
OpenHarmony + RN:Calendar日期选择功能
python
Yvonne爱编码6 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
一方_self6 小时前
了解和使用python的click命令行cli工具
开发语言·python
小芳矶6 小时前
Dify本地docker部署踩坑记录
python·docker·容器
2301_822366356 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
小郎君。7 小时前
【无标题】
python
喵手7 小时前
Python爬虫实战:数据治理实战 - 基于规则与模糊匹配的店铺/公司名实体消歧(附CSV导出 + SQLite持久化存储)!
爬虫·python·数据治理·爬虫实战·零基础python爬虫教学·规则与模糊匹配·店铺公司名实体消岐
喵手7 小时前
Python爬虫实战:国际电影节入围名单采集与智能分析系统:从数据抓取到获奖预测(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集国际电影节入围名单·从数据抓取到获奖预测