在Python中,可以使用threading模块来创建多个线程。下面是一个例子,展示了如何创建5个线程并运行它们:

import threading

# 定义一个线程执行的任务
def worker():
    print("This is a worker thread.")

# 创建5个线程
threads = []
for _ in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)

# 启动所有线程
for t in threads:
    t.start()

# 等待所有线程执行结束
for t in threads:
    t.join()

print("All threads have finished.")

在上面的例子中,worker函数定义了每个线程要执行的任务。然后通过threading.Thread类创建了5个线程,并将worker函数作为目标函数传递给了线程。创建完线程后,使用start方法启动所有线程,并使用join方法等待所有线程执行结束。最后打印出"All threads have finished."表示所有线程都已经执行完毕


原文地址: https://www.cveoy.top/t/topic/hysf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录