使用多线程编写一个并发任务案例

原创 古城微笑少年丶 2025-03-10 20:54 78阅读 0赞

以下是一个使用Python的多线程编写的并发任务案例。这个例子将创建5个线程,每个线程都会打印一条随机消息。

  1. import threading
  2. import random
  3. # 定义要并发执行的任务函数
  4. def print_message():
  5. message = "Thread #{threading.current_thread().ident}}, Random Message: {}".format(random.randint(1, 100)), threading.currentThread())
  6. print(message)
  7. # 创建5个线程,每个线程调用print_message函数
  8. threads = []
  9. for i in range(5):
  10. thread = threading.Thread(target=print_message)
  11. thread.start()
  12. threads.append(thread)
  13. # 等待所有线程完成
  14. for thread in threads:
  15. thread.join()
  16. print("All threads completed.")

这个例子展示了如何使用Python的多线程库来并发执行任务。每个线程都会打印一条随机消息,最终所有的线程都会完成并打印出它们的任务结果。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读