python多线程

1、当程序中有耗时操作时,我们应该使用多线程来进行操作。

多线程就像是多辆火车,可以在不同的轨道上同时运行。

而进程就像是火车站,正在运行的一个程序的实例。

python中多线程可以提供threading模块来实现。

简单的多线程案例:

import threading
import time

# 定义线程执行的函数
def print_numbers(message):
    for i in range(1, 3):
        time.sleep(1)  # 模拟耗时操作
        print(f"线程 {threading.current_thread().name} says {message} and prints {i}")

# 创建线程
threads = []
for i in range(3):  # 创建3个线程
    thread = threading.Thread(target=print_numbers, name=f"线程{i+1}", args=("开心的挖野菜",))
    threads.append(thread)
for i in range(3):  # 创建3个线程
    thread = threading.Thread(target=print_numbers, name=f"线程{i+1}", kwargs={"message":"挖野菜"})
    threads.append(thread)
# 启动线程
for thread in threads:
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("All threads have finished execution.")

  • 15
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿ฅ( ̳• ε • ̳)ฅ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值