使用多线程编写一个并发任务案例
以下是一个使用Python的多线程编写的并发任务案例。这个例子将创建5个线程,每个线程都会打印一条随机消息。
import threading
import random
# 定义要并发执行的任务函数
def print_message():
message = "Thread #{threading.current_thread().ident}}, Random Message: {}".format(random.randint(1, 100)), threading.currentThread())
print(message)
# 创建5个线程,每个线程调用print_message函数
threads = []
for i in range(5):
thread = threading.Thread(target=print_message)
thread.start()
threads.append(thread)
# 等待所有线程完成
for thread in threads:
thread.join()
print("All threads completed.")
这个例子展示了如何使用Python的多线程库来并发执行任务。每个线程都会打印一条随机消息,最终所有的线程都会完成并打印出它们的任务结果。
还没有评论,来说两句吧...