神奇的python的多线程

本文介绍了在Python中使用函数、类(如自定义`MyTask`类)创建和管理线程,以及线程池(`ThreadPoolExecutor`)进行并发执行的例子,展示了如何利用多线程提高程序性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过函数

import random
import threading
import time


def pr(num):
    for i in range(10):
        print(f"{num}:  i=:{i}")
        time.sleep(random.uniform(0, 1))


t1 = threading.Thread(target=pr, kwargs={"num": "t1"})
t2 = threading.Thread(target=pr, kwargs={"num": "t2"})
t1.start()
t2.start()
t1.join()
t2.join()
print("end")

通过类


class MyTask(threading.Thread):
    def __init__(self, name, count):
        super().__init__()
        self.name = name
        self.count = count
        self.daemon = False  # 默认为False设置成守护线程(True),则主线程结束后,此线程就会结束

    def run(self) -> None:
        for i in range(self.count):
            print(f"name={self.name},i={i}\n", end="")


t1 = MyTask("mytask1", 10)
t2 = MyTask("mytask2", 10)
t1.start()
t2.start()

线程池的使用



# 线程池

import time
from concurrent.futures import ThreadPoolExecutor


def pr(num):
    for i in range(10):
        print(f"{num}:  i=:{i}")
        time.sleep(random.uniform(0, 1))
    return f"{num} end"

with ThreadPoolExecutor() as executor:
    res = executor.map(pr, ["A", "B"])  # map同时提交多个相同任务
    for x in res:
        print(x)

with ThreadPoolExecutor() as executor:
    c = executor.submit(pr, "C")  # map同时提交多个相同任务
    d = executor.submit(pr, "D")  # map同时提交多个相同任务
    print(c.result())
    print(d.result())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

micro_cloud_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值