Python中的多线程模块 threading 来创建并发线程

Python中的多线程模

import threading
import time

# 定义一个线程函数,用于打印线程名称和当前时间
def print_time(thread_name, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print(thread_name, time.ctime(time.time()))

# 创建两个线程对象
thread1 = threading.Thread(target=print_time, args=("Thread-1", 2))
thread2 = threading.Thread(target=print_time, args=("Thread-2", 4))

# 启动两个线程
thread1.start()
thread2.start()

# 等待两个线程执行完毕
thread1.join()
thread2.join()

print("程序执行完毕!")

这段代码创建了两个名为 Thread-1 和 Thread-2 的线程,每个线程都调用 print_time() 函数来打印线程名称和当前时间。然后,代码使用 threading.Thread 类创建两个线程对象,并使用 start() 方法启动它们。在启动线程后,代码使用 join() 方法等待线程执行完毕,以确保程序不会在线程执行之前退出。最后,代码打印一条“程序执行完毕!”的消息来表示程序已经完成。在这个示例中,两个线程将同时运行,但由于第二个线程的时间延迟比第一个线程长,因此第一个线程的输出将比第二个线程的输出更频繁。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值