Python 创建十个独立运行的线程:后台持续执行
要创建十个独立于主程序的线程,可以使用threading模块。以下是一个示例代码:\n\npython\nimport threading\n\ndef thread_function():\n while True:\n pass\n\nthreads = []\nfor i in range(10):\n thread = threading.Thread(target=thread_function)\n thread.start()\n threads.append(thread)\n\n# 主程序继续执行其他代码...\n\n# 等待所有线程执行完毕\nfor thread in threads:\n thread.join()\n\n\n在上面的代码中,我们定义了一个thread_function函数,它包含了一个永远运行的while True循环。然后,我们循环创建十个线程,并启动它们。创建的线程会执行thread_function函数中的代码。最后,我们使用join()方法等待所有线程执行完毕。\n\n请注意,while True循环是一个无限循环,会一直执行下去。这意味着线程不会自动退出,除非我们显式地终止它们。如果你希望在线程内部能够有条件地退出循环,你可以在while循环内部添加适当的条件判断语句。
原文地址: https://www.cveoy.top/t/topic/pZm2 著作权归作者所有。请勿转载和采集!